Is there a difference between setting a property w

2019-01-26 17:24发布

Given the property declaration below, does method (A) work in exactly the same way as method (B)? I just want to check that self.yellowViewController = yellcon_New; is going via my setter, so that the old objects gets released and the new one retained.

// INTERFACE
@property(nonatomic, retain) YellowViewController *yellowViewController;

// IMPLEMENTATION (A)
self.yellowViewController = yellcon_New;

// IMPLEMENTATION (B)
[self setYellowViewController:yellcon_New];

3条回答
Explosion°爆炸
2楼-- · 2019-01-26 17:55

Yes. If you're using the @synthesize thing for that property, it's creating a -setYellowViewController: method for you.

查看更多
趁早两清
3楼-- · 2019-01-26 18:15

All of this is correct :

self.yellowViewController = yellcon_New;

And

[self setYellowViewController:yellcon_New];

Work the same. I would like to add something interesting : when you use

yellowViewController = yellcon_New;

you associate directly the value to the ivar, without going through your setter methode.

So if you have

-(void)setYellowViewController:(YellowViewController*)theYellowViewController;
{
    NSLog(@"Setting the yellow view controller");
    [yourWife askFor:beer];
    ...whatever...
    ...set the yellowViewController (retain in your case)
}

Calling

self.yellowViewController = yellcon_New;

and

[self setYellowViewController:yellcon_New];

will use the setter method (and log the message, and make your wife bring you some beer)

but

yellowViewController = yellcon_New;

will not.

It's interesting to know this in some cases.

查看更多
Fickle 薄情
4楼-- · 2019-01-26 18:15

Yes, A and B lines work the same

You can check that by using @dynamic instead of @synthesize for this property and put NSLog message in you implementation of setter method.

查看更多
登录 后发表回答