简体   繁体   中英

Setting properties defined in a super class in the initialiser

From what I learned a general rule of thumb setting values in init is a matter of using the ivars directly.

For example

@interface CustomClass

@property (nonatomic, strong) NSString *name;

@end

and then:

- (instancetype)initWithName:(NSString *)name
{
    if (self = [super init]) {
        _name = name;
    }

    return self;
}

Now so far so good. I'm interested in a slightly different case. Let's say you're subclassing a UIView and in the initialiser you want to assign a background color to that subclass. Here, the property backgroundColor is defined in the parent class. My question is: Is it bad style or potentially wrong to use self in the initialiser? Would it be better to set the background color somewhere else?

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor greenColor];
    }

    return self;
}

I believe it is perfectly fine what you are doing there. At that point, after calling super.init , the self exists, and you can use it (you are calling return self , too, so why would other references to self be wrong?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM