简体   繁体   中英

Proper way of releasing an object in objective c

-(NSString *)returnString
{
      NSString *str=[NSString new];
       return str;
}

-(void)getString {
     NSString *string=[self returnString];
     [string release];
}

Is this an appropriate/correct way of releasing a NSString ?

Also, if the lifetime of an autoreleased object is up at the end of a runloop. So can we drain a system generated autorelease pool manually? So that I can release all the autoreleased objects at the point i get a memory warning.

You should create a object with autorelease function. Try this one

-(NSString *)returnString
   {
     NSString *str= [[NSString new] autorelease];
     return str;
   }

You absolutely can drain the pool manually. Every time you drain a pool, you are indirectly sending release to all allocated objects in this pool.

Although keep in mind that you should only use Autorelease in some very specific situations. You shouldn't, for example, use it all the time to avoid worrying about releasing your objects manually.

Personally, I don't completely trust Autorelease, but when you give ownership of the object to "someone" else, it's your only option. For any other where you still own it and can release it manually, choose to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM