What's the difference between self.foo=nil and

2019-09-09 12:53发布

问题:

In the xcode, after you creating a UIViewController subclass, in the viewDidUnload method, there is a comment added by xcode:

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

Here, xcode recommends us to use self.myOutlet=nil to release object.

But in xcode4, there is a cool feature: you can just drag a Interface Builder outlet to its owner's header file, then xcode will automatically create the IBOutlet object and relevant release code in viewDidUnload method.

The problem is in above scenario, it generated code is something like this:

- (void)viewDidUnload {
    [super viewDidUnload];
    [self setFoo:nil];
}

I mention that the "self.foo = nil;" is replaced by "[self setFoo:nil];".

Does anybody know the difference? If there is no difference, why xcode4 changes it?

Thanks.

回答1:

In the executable, there is no difference between the two syntaxes. The only technical reason I can think of for Xcode to use the setter method explicitly is for compatibility with pre-Objective-C 2.0 code, which didn't support dot-syntax. I don't know why Xcode would need to support that compatibility; maybe the part of Xcode that generates the set-to-nil expression is older than Objective-C 2.0.

Or maybe the person who wrote that part of Xcode simply doesn't like dot-syntax. When dot-syntax was first introduced, a lot of people didn't like it.

http://weblog.bignerdranch.com/?p=83
http://www.cimgf.com/2008/07/08/a-case-against-dot-syntax/
http://cocoawithlove.com/2008/08/in-defense-of-objective-c-20-properties.html



回答2:

Both of those two calls will do the same thing.

self.foo = nil;

is the dot syntax version of:

[self setFoo:nil];

No performance difference, just a matter of preference on how you like to write your code.



回答3:

I think the self.foo can be a setter/getter depending on use while [self setFoo] is an explicit call to the setter.

In normal use, both should be the same.

Blog entry on dot notation in Objective C http://weblog.bignerdranch.com/?p=83