开发者

Proper way of releasing an object in objective c

-(NSString *)returnString
{
      NSString *str=[NSString new];
       r开发者_如何转开发eturn 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜