objective-c - Objective-C 中的 self

标签 objective-c

self 不能与 C++ 中的 this 完全互换吗?

它似乎适用于消息传递([ self sayHi ] 可以在任何方法中使用)。

我不太明白为什么我不能使用 self 来访问对象的私有(private)成员(在下面的示例中,我表明我不能使用 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;
}

最佳答案

其他答案几乎正确,但不完全正确。

在 Objective-C 中,没有对象 [除了 block ,但这是一个非常非常的特殊情况] 永远在堆栈上。因此,self.width 没有意义。

但是,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 的方法调用。

关于objective-c - Objective-C 中的 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695140/

相关文章:

ios - xcode UILabel 文本适合 Storyboard 但不适合设备

iphone - 无法将事件附加到段控件

objective-c - 如何设置先前创建的 NSMutableString 的文本?

objective-c - 在 xcode 的公式中使用 sin()

ios - 如何检测滚动到 UICollectionView 中的新部分?

iphone - 如何在 theos/logos 中创建自定义属性?

objective-c - 内存管理 : NSString's stringWithCString:encoding:

ios - ios中的日期转换问题

ios - 如何在现有图像上添加水印

ios - 为什么 NSTimer 可以在后台模式下延迟?