Objective C ARC release without assigning a variable
-
27-10-2019 - |
سؤال
In Objective C ARC, is it safe to do [[[MYObject alloc] init] callingSomeMethod]? Will it get released even if I dont assign to a variable?
المحلول
Yes it will. If you're nervous about it, it's easy to verify. Just put NSLog(@"it did!"); in that object's -dealloc method and check to make sure it logs.
نصائح أخرى
If you don't need the object to live after callingSomeMethod
returns, it is safe to do [[[MyObject alloc] init] callingSomeMethod]
.
If you need the object to live after callingSomeMethod
returns, then your program needs to create a strong reference to it before callingSomeMethod
returns. Examples:
- If
callingSomeMethod
sets the object as the target of anNSTimer
, you are safe becauseNSTimer
retains its target. - If
callingSomeMethod
only sets the object as the delegate of aUITableView
, you are not safe, becauseUITableView
does not retain its delegate. In that case, you must also create a strong reference to the object somewhere else.
لا تنتمي إلى StackOverflow