is self
not completely interchangeable with this
in C++?
It seems to work with message passing ([ self sayHi ]
would work within any method there).
I don't quite understand why I can't use self to access private members of an object (in the example below, I show I can't use 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 %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;
}