这里自己再进行编辑下,希望日后能看得更清楚些,也希望看原贴不是太清楚的同鞋,能看了我的理解,有更多了解:
MyObject文件:
代码
/*MyObject*/
//MyObject.h
@interface MyObject : NSObject {}
@end
//MyObject.M
@implementation MyObject
@end
MyClass文件:
代码
/*MyClass*/
//MyClass.h
@interface MyClass : NSObject {
@public
MyObject * _myObject;
}
@property (nonatomic, retain) MyObject *myObject;
@end
//MyClass.m
@implementation MyClass
@synthesize myObject = _myObject;
-(id)init{
if(self = [super init]){
MyObject * aMyObject = [[MyObject alloc] init]; //aMyObject retainCount = 1;
NSLog(@"1:aMyobject:%d",[aMyObject retainCount]);
self.myObject = aMyObject; //myObject retainCount = 2;
NSLog(@"2:aMyobject:%d",[aMyObject retainCount]);
[aMyObject release];//myObject retainCount = 1;
NSLog(@"3:aMyobject:%d",[aMyObject retainCount]);
_myObject = [[MyObject alloc] init];
NSLog(@"21:aMyobject:%d",[_myObject retainCount]);
self.myObject = [[MyObject alloc] init];
NSLog(@"22:aMyobject:%d",[_myObject retainCount]);
}
return self;
}
测试代码:
代码
/*对象引用对象时,使用存取方法和使用对象属性的区别*/
MyClass* class = [[MyClass alloc] init];
class.myObject = [[MyObject alloc] init];
NSLog(@"31: '.' class object count %d", [class.myObject retainCount] );
class->_myObject = [[MyObject alloc] init];
NSLog(@"32: '->' class object count %d", [class.myObject retainCount] );
所有输出结果:
代码
2010-10-19 11:30:28.910 Test[1293:207] 1:aMyobject:1
2010-10-19 11:30:28.910 Test[1293:207] 2:aMyobject:2
2010-10-19 11:30:28.911 Test[1293:207] 3:aMyobject:1
2010-10-19 11:30:28.911 Test[1293:207] 21:aMyobject:1
2010-10-19 11:30:28.912 Test[1293:207] 22:aMyobject:2
2010-10-19 11:30:28.912 Test[1293:207] 31: '.' class object count 2
2010-10-19 11:30:28.913 Test[1293:207] 32: '->' class object count 1
结论:
不使用self.则直接使用类属性,赋值操作。
使用self.引用属性,使用@property定义的存取操作,可以使用@synthesize 自动实现存取操作的细节
要使用某类对象的其中类的某个属性时,如上的MyClass使用MyObject中的_myObject属性时,只有_myObject为@public修饰,且使用"->"操作符时,才是对象属性的使用,其他情况一般都是使用了存取操作。