且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

@synthesize vs @dynamic,有什么区别?

更新时间:2022-02-18 04:03:41

@synthesize将为您的属性生成getter和setter方法。
@dynamic只是告诉编译器getter和setter方法不是由类本身实现的,而是在别的地方实现的(比如超类或者在运行时提供)。

@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).

@dynamic的用途是eg其子类为 NSManagedObject (CoreData),或者当您要为未定义为插座的超类定义的属性创建插座时。

Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.

@dynamic也可以用于委托实现访问器的职责。如果你自己在类中实现访问器,那么你通常不使用@dynamic。

@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.

超类:

@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;

子类:

@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;