Are these two Objective-C message expressions equivalent memory-wise?
Do the following two message expressions result in an increase of retain count in the same object?
Example 1:
iVar = [Foo aClassMethodInFoo];
[iVar retain];
Example 2:
开发者_开发知识库iVar = [[Foo aClassMethodInFoo] retain];
Example 1 is explicit in that it's iVar instance whose retain count is increased.
Example 2 seems to suggest that it's retain count of the object returned from [Foo aClassMethodInFoo]
that is increased. If that is so, then assuming aClassMethodInFoo
is a convenience method, which object do I 'release' to balance the earlier 'retain' in order not to leak memory?
Both are absolutely identical. In the first case, you're assigning the results of a method call to a variable, then calling -retain
on that variable. The net result is the variable holds the object, and you've called -retain
on the object. In the second case, you're calling -retain
on the results of a method call, and assigning the result of that to the variable. As -retain
is guaranteed to return its receiver, the net result is the variable holds the object, and you've called -retain
on the object.
In both cases, the memory semantics are precisely identical. According to the naming conventions defined in the Memory Management Programming Guide, a method named +aClassMethodInFoo
returns an autoreleased object, so your call to -retain
is correct if you're storing the results in an ivar. As such, when you're done you can call -release
on your ivar. Your question of "which object do I 'release'" is nonsensical because there's only one object here.
Assuming that the class method returns a new object rather than void, they are exactly equivalent because retain just returns self.
精彩评论