无法识别的选择器发送到实例@dynamic
unrecognized selector sent to instance @dynamic
我正在研究@dynamic 和@synthesize 的区别,所以我做了一个小的(简单的)例子:
@interface Classe : NSObject
@property (nonatomic) int value;
@end
@implementation Classe
@synthesize value;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Classe *cl = [[Classe alloc] init];
cl.value = 50;
NSLog(@"%d",cl.value);
}
return 0;
}
根据我对这个例子的理解,'synthesize' 在幕后创建了 getter 和 setter 方法,正如我们在上面看到的,我只做 cl.value = 50;
.
现在,让我们谈谈@dynamic,我听说
is merely a way to inform the system not to generate getters/setters
for the thing, that you (or someone else) will provide them for you.
好的,如果在我上面的示例中我将 @synthesize
更改为 @dynamic
,应用程序将出错并返回以下消息:
unrecognized selector sent to instance 0x10010eeb0
这是因为据说编译器不创建getters和setters方法,知道了,我怎么手动创建getters和setters方法?
好吧,你就是这么做的。如果你的属性有名字
@property (nonatomic) int value;
然后在您的实现中您只需定义方法:
-(int)value {
//your getter here
}
-(void)setValue:(int)newValue {
//Your setter here
}
@dynamic value;
告诉编译器它不应该创建默认访问器。
但您不需要 @dynamic
来完成。你可以只写一个 getter 和一个 setter。不过,您可能需要 @synthesize
。因为如果你自己指定getter和setter,编译器不会为你生成实例变量(_value
)。要做到这一点(如果你需要的话),你需要 @synthesize
.
更多信息:SO: Getters, setters and underscore property names。
我正在研究@dynamic 和@synthesize 的区别,所以我做了一个小的(简单的)例子:
@interface Classe : NSObject
@property (nonatomic) int value;
@end
@implementation Classe
@synthesize value;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Classe *cl = [[Classe alloc] init];
cl.value = 50;
NSLog(@"%d",cl.value);
}
return 0;
}
根据我对这个例子的理解,'synthesize' 在幕后创建了 getter 和 setter 方法,正如我们在上面看到的,我只做 cl.value = 50;
.
现在,让我们谈谈@dynamic,我听说
is merely a way to inform the system not to generate getters/setters for the thing, that you (or someone else) will provide them for you.
好的,如果在我上面的示例中我将 @synthesize
更改为 @dynamic
,应用程序将出错并返回以下消息:
unrecognized selector sent to instance 0x10010eeb0
这是因为据说编译器不创建getters和setters方法,知道了,我怎么手动创建getters和setters方法?
好吧,你就是这么做的。如果你的属性有名字
@property (nonatomic) int value;
然后在您的实现中您只需定义方法:
-(int)value {
//your getter here
}
-(void)setValue:(int)newValue {
//Your setter here
}
@dynamic value;
告诉编译器它不应该创建默认访问器。
但您不需要 @dynamic
来完成。你可以只写一个 getter 和一个 setter。不过,您可能需要 @synthesize
。因为如果你自己指定getter和setter,编译器不会为你生成实例变量(_value
)。要做到这一点(如果你需要的话),你需要 @synthesize
.
更多信息:SO: Getters, setters and underscore property names。