Do I need getters and setters if i'm depending on garbage collection in objective-c
New to Cocoa and Objective-c.
Do I need getters and setters if I'm depending on garbage collection?
For example is it safe to just modify instance variables directly without the dot syntax?
And in the dealloc method can I sent them to nil instead o开发者_如何学Pythonf release (or do I even have to release them)?
Property (Getters and setters) is a mean of encapsulation, and ivar is an implementation detail.
Accessing via properties allow you to change the internal design while keeping the interface unchanged.
Whether the program has GC enabled or not, you shouldn't access ivar directly externally (internally is fine).
(Also, the -dealloc
method is ignored if GC (not ARC) is enabled. You could implement -finalize
. But the GC should be smart enough to clean the no-longer-needed ivars, whether to set them to nil
or not.)
From within the class itself you can directly modify the private variables of course. Think about accessors mainly to expose a public interface and avoid other classes to modify directly your object. This comes from the Object Oriented Paradigm and not with the memory management.
About the release it is better to understand clearly how it works using the retain count and what have a role on that count. Some method like init increase retains the object and some other do not. A lot static methods that return new ready to use object like imageWithNamed: return an autorelease object that you have to retain explicitly to own them.
The best is to release and set to nil when you have transfer the ownership to another object (ex. an array)
ex.
NSString *myName = @"zgueb";
NSArray *myFamily = [[NSArray alloc] initWithObjects:myName, nil];
// now myName is retained by myFamily, i can release it
[myName release];
myName = nil;
Is it clear.
Vince.
精彩评论