Objective-C, interface declarations with properties

前端 未结 4 1066
闹比i
闹比i 2020-12-21 05:48

In the following common sample,

////
@interface MyObject : NSObject
{
 @public
  NSString * myString_;
}

@property (assign) NSString * myString;
@end

@impl         


        
4条回答
  •  感动是毒
    2020-12-21 06:23

    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.

    1. The ivar declaration is optional, not required. Compiler will generate it automatically.
    2. You should set the ivar as @protected or @private to encapsulate it correctly. (at least there is no reasonable reason)
    3. I recommend to use 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

提交回复
热议问题