ObjC : difference between self.obj and obj
What is the difference between self.obj
and obj
in objective C?
I'm asking this because when I write [view method]
it's fine
but 开发者_Python百科when trying [self.view method]
it's an infinite loop
In fact the code is the following:
//---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;
The problem is that [self.view addSubview:button]
gives an infinite loop.
Using obj
is just what it looks like: direct variable access.
However, self.obj
is not what it looks like. Instead, it is context-dependent syntactic sugar for a call to an accessor method. By convention, the setter method would be setObj:
and the getter obj
, though it is possible to override this. So typically self.obj
is equivalent to either [self obj]
or [self setObj:x]
depending on whether you're reading from the value or assigning to it.
In your example, when you put [self.view method]
, what you are really doing is [[self view] method]
. Without knowing more about the context in which you're using this, it's hard to say why it's giving you an infinite loop, although one obvious case that would do that is if you were making this call inside the accessor method for view
.
When you're using '.' you're accessing property. And when you're typing [view method] you're accessing the variable named view. See my answer for this question.
for example:
-(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)
}
精彩评论