Objective c ObjC:self.obj和obj之间的区别
在目标C中,Objective c ObjC:self.obj和obj之间的区别,objective-c,Objective C,在目标C中,self.obj和obj之间有什么区别 我问这个问题是因为当我写[view method]时,它很好 但是当尝试[self.view方法]时,这是一个无限循环 事实上,代码如下所示: //---create a UIView object--- UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]; view.backgroundColor = [UIColor l
self.obj
和obj
之间有什么区别
我问这个问题是因为当我写[view method]
时,它很好
但是当尝试[self.view方法]
时,这是一个无限循环
事实上,代码如下所示:
//---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]
会给出一个无限循环。当您使用“.”时,您正在访问属性。当您键入[view method]时,您正在访问名为view的变量。请看我的问题答案
例如:
-(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)
}
当您使用“.”时,您正在访问属性。当您键入[view method]时,您正在访问名为view的变量。请看我的问题答案 例如:
-(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)
}
使用
obj
就是它看起来的样子:直接变量访问
然而,self.obj
并不是它看起来的样子。相反,它是上下文相关的语法糖,用于调用访问器方法。按照惯例,setter方法将是setObj:
和getterobj
,尽管可以覆盖它。因此,典型的self.obj
相当于[self-obj]
或[self-setObj:x]
,这取决于您是从值中读取还是分配给它
在您的示例中,当您放置
[self.view方法]
时,您真正做的是[[self-view]方法]
。如果不了解使用它的上下文,很难说为什么它会给你一个无限循环,尽管一个明显的例子是如果你在视图的访问器方法中使用obj
调用它,它看起来就是这样的:直接变量访问
然而,self.obj
并不是它看起来的样子。相反,它是上下文相关的语法糖,用于调用访问器方法。按照惯例,setter方法将是setObj:
和getterobj
,尽管可以覆盖它。因此,典型的self.obj
相当于[self-obj]
或[self-setObj:x]
,这取决于您是从值中读取还是分配给它
在您的示例中,当您放置[self.view方法]
时,您真正做的是[[self-view]方法]
。如果不了解使用它的上下文,很难说为什么它会给你一个无限循环,尽管一个明显的例子是如果你在视图的访问器方法中进行调用,实际上代码如下://--创建一个UIView对象--UIView*视图=[[UIView alloc]initWithFrame:[UIScreen Main Screen].applicationFrame];view.backgroundColor=[UIColor lightGrayColor];UIButton*button=[UIButton button WithType:UIButtonTypeLoundRect];[view addSubview:button];self.view=view;问题是[self.view addSubview:button]给出无限循环事实上,代码如下://--创建UIView对象--UIView*视图=[[UIView alloc]initWithFrame:[UIScreen Main Screen].applicationFrame];view.backgroundColor=[UIColor lightGrayColor];UIButton*button=[UIButton button WithType:UIButtonTypeLoundRect];[view addSubview:button];self.view=view;问题是[self.view addSubview:button]给出了一个无限循环该代码存在于什么方法中?是什么导致调用它?该代码存在于什么方法中?是什么导致调用它?