views:

68

answers:

2

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 of release (or do I even have to release them)?

+2  A: 

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.

(Also, the -dealloc method is ignored if GC 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.)

KennyTM
Right now I basically have one App Controller class. So in this case I shouldn't need getters and setters to modify it's own variables right?
Chris
@Chris: There no need to use properties inside the AppController class (assuming the property is @synthesize-d). But from outside, you have to use properties.
KennyTM
A: 

Hi, 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.

Vincent Zgueb