天天看点

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