I'm using ASIHTTPRequest library and I want to be sure if I use it in a good way from the memory management point of view. I create:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];
I guess that according to the naming convention I don't have to retain request object, right? but when I look at the code of requestWithURL:someUrl method I can see:
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
so the returned object is autoreleased. Shouldn't I retain it in my code?
The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it.
An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.
An autorelease pool stores objects that are sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.
Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.
If you use autorelease object within a method, you should not retain, so this is okay:
- (void) myMethodDoRequest
{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];
// use request within this scope only
}
If you want to store the autorelease object in ivar, you have to retain to expand the lifecycle of the object, and latter release to avoid leak:
@interface MyClass
{
ASIFormDataRequest *request;
}
and
- (void) myMethodStoreRequest
{
[request release];
request = [[ASIFormDataRequest requestWithURL:someUrl] retain];
}
- (void) dealloc
{
[request release];
}
In general no - as it is autoreleased, its retained by the autorelease pool and that will release it when it goes out of scope. However, you can retain and then release it if you are in a situation where you need the extra security that provides.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With