将ivar设置为自定义子对象不起作用

时间:2012-04-26 22:33:31

标签: iphone objective-c ios cocoa-touch automatic-ref-counting

我可能忽略了一些小事,但我似乎无法弄明白。

我试图将自定义类的实例传递给另一个自定义类的实例。 注意:我使用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时,我仍然会收到错误消息。我错过了什么?

1 个答案:

答案 0 :(得分: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