Objective-C中的self
在C中自我不完全可以互换吗?
它似乎与消息传递一起工作([self sayHi]可以在任何方法中工作). 我不太明白为什么我不能使用self访问对象的私有成员(在下面的示例中,我显示我不能使用self.width) #import <Foundation/Foundation.h> // Write an Objective-C class @interface Rectangle : NSObject { int width ; } -(int)getWidth; -(void)setWidth:(int)w; -(void)sayHi; -(void)sayHi:(NSString*)msg ; @end @implementation Rectangle -(int)getWidth { // <b>return self.width ; // ILLEGAL,but why?</b> // why can't I return self.width here? // why does it think that's a "method"? return width ; } -(void)setWidth:(int)w { // <b>self.width = w ; // ILLEGAL</b> // again here,I CAN'T do self.width = w ; width = w ; } -(void)sayHi { puts("hi"); } -(void)sayHi:(NSString*)msg { printf( "Hi,and %sn",[ msg UTF8String ] ) ; } @end int main (int argc,const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Rectangle* r = [ Rectangle alloc ] ; [ r sayHi ] ; [ r setWidth:5 ] ; printf( "width is %dn",[ r getWidth ] ) ; [pool drain]; return 0; } 解决方法
其他答案几乎是正确的,但并不完全正确.
在Objective-C中,没有任何对象[保存为块,但这是一个非常特殊的情况]永远在堆栈中.因此,self.width没有意义. 但是,自我>宽度确实有效.由于self是对堆上分配的有效结构的引用,因此使用 – >运算符来获取成员变量是有道理的. 但是,在Objective-C的背景下,它通常也没有意义.也就是说,Objective-C通常假定保留封装的哲学.也就是说,您通常不会直接进入对象并使用实例变量 – 内部状态.相反,您使用访问器来获取/设置状态.通过这样做,对象(和子类)可以根据需要自定义getter / setter行为. (这包括键值观察和键值编码等机制). self.width恰好等同于[self width]或[self setWidth:… something ……]是上面的后果.那就是 .用于访问Objective-C类实例成员的运算符未以其他方式使用,并且可能因为属性访问的简写而被重载. 但是,属性访问和调用getter / setter方法之间几乎没有区别.因此,点表示法与方法调用同义. 在代码的上下文中,实例变量可以在类实现中透明地访问,并且没有前缀. 因此,你会使用width = 5.0;而不是self.width = 5.0;,通常.当然,后者确实等同于使用Objective-C 2.0的方法调用,原因如上所述. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |