是self
在C++中不能完全与this
互换?self in objective-c
它似乎与消息传递([self sayHi]将工作在任何方法)。
我不明白为什么我不能使用自我访问对象的私有成员(在下面的例子中,我告诉我不能使用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 { // return self.width ; // ILLEGAL, but why?? // why can't I return self.width here? // why does it think that's a "method"? return width ; } -(void)setWidth:(int)w { // self.width = w ; // ILLEGAL // again here, i CAN'T do self.width = w ; width = w ; } -(void)sayHi { puts("hi"); } -(void)sayHi:(NSString*)msg { printf("Hi, and %s\n", [ 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 %d\n", [ r getWidth ]) ; [pool drain]; return 0; }
哦,他真的很...甜。所以点符号只是简单的翻译成方括号内容。谢谢!这个答案有帮助。 – bobobobo
Apple's Cocoa Coding Guidelines(http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282)声明'get'前缀只能在通过方法参数中指定的指针间接返回多个值时使用。例如,NSColor有一个名为'getRed:blue:green:alpha'的方法,该方法通过给定的'CGFloat'指针返回颜色的RGBA分量。 – hbw
类别。点符号实际上与'@ property'完全正交。实际情况是,Objective-C对象从来不在堆栈中(除了块以外,这是一个非常特殊的情况),因此,访问成员的'.'没有任何意义。 – bbum