ObjC:self.obj和obj之间的区别

时间:2011-03-13 13:37:26

标签: objective-c

目标C中self.objobj之间的区别是什么?

我问这个是因为当我写[view method]时很好

但在尝试[self.view method]时,这是一个无限循环

实际上代码如下:

//---create a UIView object--- 
UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]; 
view.backgroundColor = [UIColor lightGrayColor]; 
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[view addSubview:button]; 
self.view = view;

问题是[self.view addSubview:button]给出了无限循环。

2 个答案:

答案 0 :(得分:3)

使用obj就是它的样子:直接变量访问。

但是,self.obj 它看起来像什么。相反,它是一个依赖于上下文的语法糖,用于调用访问器方法。按照惯例,setter方法可以是setObj:和getter obj,但可以覆盖它。因此,self.obj通常等同于[self obj][self setObj:x],具体取决于您是从值读取还是分配给它。

在您的示例中,当您放置[self.view method]时,您实际所做的是[[self view] method]。如果你不了解更多关于你正在使用它的上下文,很难说它为什么会给你一个无限循环,尽管一个明显的例子是如果你在里面进行这个调用 view的访问器方法。

答案 1 :(得分:2)

当你使用'。'时你正在访问财产。当您输入[view method]时,您正在访问名为view的变量。请参阅我对this问题的回答。

例如:

-(void) doSmth {
    UIView* view = [[UIView alloc] init];
    [view method];      //sends message 'method' to view variable declared in this function 
    [self.view method]; //sends message to instance variable of self (accessing it via generated accessor)
}