Are all objects in the iOS automatically added to the auto release pool?

201 Views Asked by At

Are all objects in the iOS automatically added to the autorelease pool?When ARC? If no, which one will be added & which one not?

eg:

{
  NSString *str = [[NSString alloc] init];
  NSString *str2 = [NSString string];
}

+ (NSString *)string {
  return [[NSString alloc] init];
}

str2 will be added to autorelease pool because it creates by a method that name as 'copy/mutableCopy/alloc/new'. So it does not create by self. But I don't know is str will be added or not and why?

2

There are 2 best solutions below

0
ChokWah On

The answer is NO. In fact, which will be added auto release pool is obj of method "string".

// ARC
{
  NSString __strong *str = [[NSString alloc] init]; // STEP A
  NSString __strong *str2 = [NSString string]; //  STEP B
}//  STEP Finish


+ (NSString *)string {
  id obj = [[NSString alloc] init];
  return obj;
}

Like this may help you understand.In ARC, object has __strong modifier(default).Because a object must has a strong pointer point to it, or it die.

STEP A : str create a NSString object and strong point to itself. STEP B : str2 not create but strong point to a object which is obj.obj created by NSString in method string, because it needs return, so added to auto release pool. And str2 strong point to obj, so obj can't release by auto release pool, there still a strong pointer point to it.

STEP Finish,str,str2 out of method, no more strong pointer .So they had release. At STEP B, why will needs auto release pool? Because if don't put obj into auto release pool, it will release by compiler, just like str in the STEP Finish.

All this from the book "Pro multithreading and memory management for iOS and OS X".

Forget my poor English.

0
newacct On

ARC makes no guarantees as to what objects are added to the autorelease pool and what objects are not. It is very possible that neither of the objects in your example are ever added to the autorelease pool under ARC.