开发者

understanding self. in objective C

It's been 3 days since I've programmed in objective-C and I still don't quite understand the concept of self.

When should we use a self. in an implementation code? If I understand this correctly if I have defined it as a property then I should use self. But then the question is why? I've been reading many i-phone programming books but none doesn't seem to give me a strong and clear answer. Is sel开发者_开发技巧f the same as this in other programming languages such as java?


self in Objective C is a pointer to the receiver of the current message, so it is a very similar concept to this in Java.


self is roughly equivalent to this in other languages. Also, the dot-notation introduced in Objective-C 2.0 can mask what is really happening.

self.foo = 4;
NSInteger someInt = self.foo;

The above is the same as

[self setFoo:4];
NSInteger someInt = [self foo];

self is actually just a variable that is automatically passed to class and instance methods. This is what makes it possible to do:

self = [super init];
if (!self) return nil;


self in Objective-C is the same as this in Java.

In both cases, self and this are special variables inside an object which refers to the object itself. Use this when accessing properties or calling methods on the same object, or when calling an outside method to pass the object as a parameter.

If you think of self and this as the same thing, you will not have any problems. Of course, you can't actually use them interchangeably since each language recognizes only one of them.


If you're used to programming in Java, think of self as Java's this.
For example, you'd use self in a class when you want to refer to something to do with that class- for example, in the class Car, self.wheels.


If you have defined a property and synthesised it using self.foo = bar will call a setter that has been generated for you. If you just do foo = bar you assign to your variable without going through the setter method. This means you won't take advantage of retain if the property was declared with retain or synchronisation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜