无法识别的选择器发送到实例@dynamic

时间:2015-03-17 12:22:52

标签: ios objective-c 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;
}

据我所知,我的例子就是“合成”。在幕后制作getter和setters方法,正如我们上面所见,我只做cl.value = 50;

现在,让我们谈谈@dynamic,我听说

  

仅仅是一种通知系统不生成getter / setter的方法   对于那件事,你(或其他人)会为你提供它们。

好的,如果在上面的示例中我将@synthesize更改为@dynamic,则应用程序将返回错误,返回以下消息:

  

无法识别的选择器发送到实例0x10010eeb0

这是因为有人说编译器没有创建getter和setters方法,知道这一点,我怎样才能手动创建getter和setters方法?

1 个答案:

答案 0 :(得分:2)

嗯,你就是这么做的。如果您的财产有名称

@property (nonatomic) int value;

然后在您的实现中,您只需定义方法:

-(int)value {
    //your getter here
}

-(void)setValue:(int)newValue {
    //Your setter here
}

并且您不需要@dynamic来执行此操作。你可以写一个getter和一个setter。您可能需要@synthesize。因为如果您指定了自己的getter setter,编译器将不会为您生成实例变量(_value)。为了做到这一点(如果你需要),你需要@synthesize

有关它的更多信息:SO: Getters, setters and underscore property names