limit on using autorelease pools in ios
How many autorelease you can create in your application? Is there any limit?
I searched for an answer in google, but didn't get any useful info.
And
int main(){
NSAutoreleasepool *pool = [NSAutoreleasepool alloc]init];
NSString *str = [NSString alloc]init];
[pool drain];
}
In google, i found this sample in almost all the articles. With the above code, if we do analyze in Xcode it throws memory leak. Instead if we alloc str in this way NSString *str = [NSString alloc]init]autorelease;
then it does not throw any memory leak.
Which way is correct.
Also in the above code, i found that when [pool drain] statement is executed, then the variable str is released. When we write the same code using "@autorelease" keyword instead of NSAutoreleasePool, what happens. I mean there won't be any statement like [pool drain] if we use @autorelease.
I mean in this way
int main(){
@autorelease{
NSString *str = [NSString alloc]init];
}
}
Thanks Jithen
The use of an NSAutoreleasePool
or @autorelease
is not for fixing memory leaks. Their use is to help control the scope of when autoreleased objects are released. You need to do proper memory management regardless of whether you use any autorelease pools or not.
In the first block of code you posted, you get a memory leaks because you allocate a string but you never call release
on the object. In this case, str
is not an autoreleased object. The autorelease pool has no effect on this object.
When you added the call to autorelease
on the string, then the object gets queued to be autoreleased at some point. Draining the autorelease pool triggers that release.
Your last code using @autorlease
is identical to the first block of code. You don't properly release str
so it will leak. But again, this has nothing to do with the autorelease pool.
Enabling ARC would fix your issue for the first and last blocks of code you posted. ARC would take care of releasing str
for you.
Edit: And as stated in the comment above, you can have as many autorelease pools as you need to control when autoreleased objects are actually released.
链接地址: http://www.djcxy.com/p/72764.html上一篇: PyObjc自动释放池