开发者

Objective C - Basic question? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why use 'self.' when its not forced?

What is the difference between these 2 blocks of code?

@property (nonatomic, retain) MyObject *myObject;

MyObject *obj = [[MyObject alloc] init];
self.myObject = obj;
[obj release];

MyObject *obj = [[MyObject alloc] init];
myObject = obj;
[obj release];

EDIT:

Does it m开发者_Python百科ean that on the second block I don't need to release "obj" ?


In the first case, self.myObject implies that myObject is a @property, and when you assign to it with self.myObject = obj, that property's setter will get invoked. Often, that setter is automagically generated by the compiler with the @synthesize directive. If that property's autogenerated setter is flagged with retain, then whatever assigned to it (in this case, obj) will be retained by the property.

In the second case, myObject may or may not be a property. Regardless, this is a simple assignment. No retain is done.


The first one calls the accessor of self, and the second doesn't. A logical equivalent for the first block might be:

MyObject *obj = [[MyObject alloc] init];
[self setMyObject:obj];
[obj release];

As you can see, a method invocation happens there on the second line, which doesn't happen in the second line of your second example.


self is used to access class/instance properties (an accessor). For example, if you defined a property in your header file (using @property), it is good practice (for code readability amongst other things) to use self.myClassProperty. Local variables, like variables declared inside functions (or even outside functions as members), are accessed without the self keyword.

Similar SO Question here: Objective-C - When to use 'self'


that depends on how you have declared myObject in your header file. The prevalent practice in the the boilerplate code makes those to semi equivalent.

the difference is that 1 is guaranteed to be using the property named myObject, and therefore will trigger the getter and setter functions.

the second one accessed the the instance variable and is not guaranteed to use the getter and setter functions. if your ivar has the same name as the property it should use the setter and getter functions.

the way to make this more explicit is to prepend something to all of your ivars. (eg mMyObject) and then use a mutator in @synthesize @synthesize myObject = mMyObject;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜