天天看點

property和_property的一些小結

在.h檔案中:

@interface MyClass:NSObject

{

      MyObjecct *_myObject;

}

@property(nonamtic, retain) MyObjecct *myObject;

@end

在.m檔案中

@implementation MyClass

@synthesize myObject=_myObject;

- (void)dealloc

{

    [_myObject release];

    [super dealloc];

}

@end

通過最近google了一些文章,如果大家觀後有自己看法希望能留言 _myObject是執行個體變量,相當于C++中self-> myObject self. myObject相當于 [self myObject];是一個消息,也有說是屬性 http://stackoverflow.com/questions/5466496/why-rename-synthesized-properties-in-ios-with-leading-underscores

myObjec t和 _myObject是用來差別 執行個體變量消息。一般來說,應該使用setter和getter的屬性,而不是直接通路執行個體變量。 當你寫一個setter方法,該方法不能自身使用setter,否則你會産生無限遞歸,并且發生崩潰。setter調用自身,再次調用自身,直到堆棧溢出。 http://www.iphonedevsdk.com/forum/iphone-sdk-development/98273-feeling-confused-about-_property-and-property.html

寫成這樣:

@interface MyClass
@property (nonatomic, retain) NSString* myProperty;
- (NSString*)someOtherMethod;
@end

@implementation MyClass
@synthesize myProperty = _myProperty; // setter and ivar are created automatically

- (NSString*)myProperty {
    return [_myProperty stringByAppendingString:@" Tricky."];
}

- (NSString*)someOtherMethod {
    return [self myProperty];
}           

http://stackoverflow.com/questions/9541828/property-and-setters-and-getters

http://stackoverflow.com/questions/4172810/what-is-the-difference-between-ivars-and-properties-in-objective-c