2012-04-26 44 views
1

我可能忽略了一些小事,但我似乎无法弄清楚。将伊娃设置为自定义亚类对象不工作

我正在尝试将自定义类的实例传递给另一个自定义类的实例。 注:我使用ARC *

第二个自定义类设置:

#import "OneArtsDay.h" 

@interface SocialButton : UIButton {  
    OneArtsDay *artsDay; 
} 

@property (nonatomic) OneArtsDay *artsDay; 

- (void)setArtsDay:(OneArtsDay *)day; 

@end 

#import "SocialButton.h" 

@implementation SocialButton 
@synthesize artsDay; 

- (void)setArtsDay:(OneArtsDay *)day { 
    if (day ==nil) { 
    NSLog(@"Error, cannot set artsDay"); 
    } 
    else { 
    artsDay = day; 
    } 
} 

@end 

现在,当我在代码中调用这些命令:

SocialButton *social = [[SocialButton alloc] init]; 
    OneArtsDay *day = [[OneArtsDay alloc] init]; 
    //Do things with day here// 
    [social setArtsDay:day]; 

我仍然有一个错误,当我尝试访问属性OneArtsDay * artsDay。我错过了什么?

+3

当你说它不起作用你是什么意思?什么不起作用? – 2012-04-26 22:37:59

+0

而不是(非原子)使用(强,非原子),所以它会保持一个强大的指针,你的对象。这仅适用于ARC。另请使用setter self.artsDay = day; – 2012-04-26 23:05:22

+0

我给出的错误是一个'NSInvalidArgumentException ..无法识别的选择器发送到实例..',并发生当我尝试访问属性OneArtsDay * artsDay – achi 2012-04-27 00:05:24

回答

2

该属性应该声明为强。以下是我如何编码同样的事情:

#import "OneArtsDay.h" 

@interface SocialButton : UIButton 

// property decl gives me the file var and the public getter/setter decls 
// strong tells ARC to retain the value upon assignment (and release the old one) 
@property (nonatomic, strong) OneArtsDay *artsDay; 

@end 


#import "SocialButton.h" 

@implementation SocialButton 

// _underscore alias let's me name stack vars and prams the same name as my property 
// without ambiguity/compiler warnings 

@synthesize artsDay=_artsDay; 

- (void)setArtsDay:(OneArtsDay *)artsDay { 
    if (artsDay==nil) { 
     NSLog(@"Error, cannot set artsDay"); 
    } else { 
     _artsDay = artsDay; 
    } 
} 

@end 
+0

虽然这是我该怎么做,它实际上是否改变任何东西?我认为'__strong'是默认的变量限定符,这意味着OP显式声明的伊娃实际上是在声明一个'__strong' ivar。在ARC中,'strong'更适合,然后'保留',即使它们是同义词。 – 2012-04-26 23:04:21

+0

该类需要在ARC中保留一个“强”指向该对象的指针,否则它可能会被释放。 – 2012-04-26 23:08:54

+0

是的。每弧有回火。谢谢。将编辑。 – danh 2012-04-26 23:37:19

相关问题