objective-cmultithreadingpointersmethodssynthesize

How dangerous is it to use pointer-style assignment versus setter-methods in Objective-C?


Lets say I have a simple class like the following:

@interface A { 
// @public
    int var;
}
// @property(some_property) int var;
@end

When I want to access the variable var, I have some options. If I make var public, I can do this:

A objectA = [ [ A alloc ] init ];
NSLog( @"%d", objectA->var );
objectA->var = someNumber;

If I make it a property instead, I'll have to do something more like this:

A objectA = [ [ A alloc ] init ];
NSLog( @"%d", objectA.var ); // dot-syntax
NSLog( @"%d", [ objectA var ] ); // get-syntax
[ objectA setVar: someNumber ];

I've tried both and they work fine but my question is how dangerous is it to use the old-style pointer notation to access variables inside of an object? Will I have to worry about things later on that I should take care of now by standardizing my accessing of methods? Or can I get away with doing it however I want so long as it works?


Solution

  • I'll throw my own 2 cents in since a comment of mine on another question started a similar discussion a few days ago.

    You should always use accessor methods to set and get an object's properties outside of the implementation of that object's class. You should almost always use accessor methods to access a class's properties even inside the implementation of said class.

    Here is a list of some reasons why:

    Remember that I used an 'almost' qualifier regarding using direct ivar access inside a class's implementation. If you implement custom accessor methods (as opposed to @synthesizing a property), you will have to directly access the ivar inside the accessors' implementations, of course. Also, there are some who disagree, but it's a good idea (and Apple's recommendation) to directly set ivars inside a class's initializer (-init) and dealloc method(s). The reason for this is that you may want to avoid setter side effects while a class is not completely initialized. For example, you don't want KVO observers to be notified of a change when they may find the notifying object in an inconsistent/partially initialized state.