In the following common sample,
////
@interface MyObject : NSObject
{
@public
NSString * myString_;
}
@property (assign) NSString * myString;
@end
@impl
That's just a problem about point of view. If you access ivar directly, it's you're accessing it internally. If you're using property, you're not accessing ivar (semantically). You're using accessing method of the object. So you're handling the self as like external object which the internal is unknown.
This is encapsulation problem of Object-Oriented paradigm.
And I recommend some tricks when using properties.
@protected or @private to encapsulate it correctly. (at least there is no reasonable reason)nonatomic if you don't need threading lock when accessing the property. Threading lock will decrease performance greatly, and may cause strange behavior in concurrent execution code.You can use this code to do same thing.
@interface MyObject : NSObject
@property (assign,nonatomic) NSString * myString;
@end
@implementation MyObject
@synthesize myString;
@end
And this will be transformed roughly something like this.
@interface MyObject : NSObject
{
@private
NSString* myString; // Ivar generated automatically by compiler
}
@end
@implementation MyObject
// Methods with thread synchronization locking generated automatically by compiler.
- (NSString*)myString { @synchronized(self) { return myString; } }
- (void)setMyString:(NSString*)newMyString { @synchronized(self){ myString = newMyString; } }
@end
In fact, I'm not sure about synchronization lock with assign behavior directive, but it's always better setting it nonatomic explicitly. Compiler may optimize it with atomic operation instruction instead of locking.
Here is reference document about the properties: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17