关于Ojbective-C的self.的用法总结

原贴:http://www.cocoachina.com/bbs/read.php?tid=12850&page=4#

这里自己再进行编辑下,希望日后能看得更清楚些,也希望看原贴不是太清楚的同鞋,能看了我的理解,有更多了解:

 

MyObject文件:

/* MyObject*/

// MyObject.h
@interface MyObject : NSObject {}
@end
// MyObject.M
@implementation MyObject
@end

 

MyClass文件:

ExpandedBlockStart.gif 代码
/* 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;
}

 

 

测试代码:

ExpandedBlockStart.gif 代码
/* 对象引用对象时,使用存取方法和使用对象属性的区别 */
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] );

 

 

所有输出结果:

ExpandedBlockStart.gif 代码
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修饰,且使用"->"操作符时,才是对象属性的使用,其他情况一般都是使用了存取操作。

 

 

 

 

 

转载于:https://www.cnblogs.com/simalone/archive/2010/10/19/1855444.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值