سؤال

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 an NSTimer, you are safe because NSTimer retains its target.
  • If callingSomeMethod only sets the object as the delegate of a UITableView, you are not safe, because UITableView does not retain its delegate. In that case, you must also create a strong reference to the object somewhere else.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top