@dynamic 使用的常见情况是什么?

发布于 2024-10-08 18:23:56 字数 612 浏览 0 评论 0原文

之前有一篇帖子关于@synthesize和@dynamic的区别。

我想从通常如何使用@dynamic的角度来了解更多关于dynamic的知识。

通常我们将@dynamic与NSManagedObject一起使用,

// Movie.h
@interface Movie : NSManagedObject {
}
@property (retain) NSString* title;
@end

// Movie.m
@implementation Movie
@dynamic title;
@end

实际上根据对@dynamic的理解,编译时并没有生成getter/setter,所以需要实现自己的getter/setter。

我的问题是,在这个 NSManagedObject 案例中,超类 NSManagedObject 中 getter/setter 的粗略实现是什么?

除了上述情况外,还有多少情况需要使用 @dynamic ?

谢谢,

There is previous post about difference of @synthesize and @dynamic.

I wanna to know more about dynamic from the perspective of how to use @dynamic usually.

Usually we use @dynamic together with NSManagedObject

// Movie.h
@interface Movie : NSManagedObject {
}
@property (retain) NSString* title;
@end

// Movie.m
@implementation Movie
@dynamic title;
@end

Actually there are no generated getter/setter during compiler time according to understanding of @dynamic, so it is necessary to implement your own getter/setter.

My question is that in this NSManagedObject case, what is the rough implementation of getter/setter in super class NSManagedObject ?

Except above case, how many other cases to use @dynamic ?

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空宴 2024-10-15 18:23:57

@dynamic 向编译器表明您计划为访问器提供您自己的实现,即使编译器当前无法看到它们。如果您省略 @dynamic 并且不使用 @synthesize,则会发生以下两种情况之一:

  1. 如果您只提供了一半的访问器(例如,没有readwrite 属性上的 setter),或者您正在使用 GCC,编译器会警告您。
  2. 如果您使用 Clang 编译代码,则会自动为您生成适当的访问器。(默认不支持 Synthesize。)

因此,@dynamic 是对于防止编译器执行上述任一操作很有用。如果您以非常动态的方式实现属性(例如使用运行时函数),这也可能会派上用场,但这很少有必要。

@dynamic indicates to the compiler that you plan to provide your own implementation for the accessor(s), even if the compiler can't currently see them. If you omit @dynamic and don't use @synthesize, one of two things will happen:

  1. If you've only provided half an accessor (for instance, a getter without a setter on a readwrite property), or you're using GCC, the compiler will warn you.
  2. If you're using Clang to compile your code, proper accessors will be automatically generated for you. (Synthesize-by-default is not officially supported.)

@dynamic is therefore useful to prevent the compiler from doing either of the above. This might also come in handy if you implement a property in a very dynamic way, like with runtime functions, but that's rarely necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文