Objective-C memory management: how do you release the memory when you return an allocated instance? - objective-c

How do you release the memory in this situation? Do you have to?
- (NSString *) whatHappensHere {
NSMutableString * mutableString = [[NSMutableString alloc] initWithString:#"Hello"];
// ....
// more code ...
// ...
return mutableString;
}

With autorelease
- (NSString *) whatHappensHere {
NSMutableString * mutableString = [[NSMutableString alloc] initWithString:#"Hello"];
[mutableString autorelease];
return mutableString;
}

As willcodejavaforfood said, the convention is that any newly-allocated object returned from a method should be autorelease'd before being returned. This tells the Objective-C runtime that if nobody takes ownership of it with retain before (in most cases) the current iteration of the application event loop ends, it should be freed.
If it's just used locally in the calling function or returned up the stack, that works great and it gets freed sooner or later. If someone ends up wanting to keep it around, then they have to retain it and so will know they have to release it themselves later on.
(In fact, most of the non-init* utility constructors for ObjC base classes like strings, etc, do just that, or at least something functionally equivalent.)

Related

Does ARC ever inject unconventional code?

Does ARC ever inject retain and release calls that you generally wouldn't see in a non-ARC environment?
For example, explicitly releasing an object from a getter:
- (NSArray *)dummyArray {
return [[NSArray alloc]init];
}
- (void)useDummyArray {
NSArray * arr = [self dummyArray];
//do something with arr
[arr release]; //unconventional injection of release.
}
Would ARC ever generate a release statement like the code above or would it autorelease the array returned by [self dummyArray];
The beauty of ARC is that you don't know, or need to know. However, you can give hints to the ARC static analyzer:
-(NSArray *) dummyArray NS_RETURNS_RETAINED { // this tells ARC that this function returns a retained value that should be released by the callee
return [[NSArray alloc] init];
}
-(NSArray *) otherDummyArray NS_RETURNS_NOT_RETAINED { // this tells ARC that the function returns a non-retained (autoreleased) value, which should NOT be released by the callee.
return [[NSArray alloc] init];
}
However, NS_RETURNS_NOT_RETAINED is the default, as long as your function name doesn't begin with init, in which NS_RETURNS_RETAINED becomes default.
So, in your specific scenario, it will almost always return an autorelease'd value. One major reason for this is support for interpolation with non-ARC code, which could result in leaks.

Lifetime of weak local variables with ARC

If I have a piece of code that looks like this:
- (void)testSomething
{
__weak NSString *str = [[NSString alloc] initWithFormat:#"%#", [NSDate date]];
NSLog(#"%#", str);
}
the output will be (null) because there are no strong references to str and it will be immediately released after I allocate it. This makes sense and is spelled out in the Transitioning to ARC guide.
If my code looks like this:
- (void)testSomething
{
__weak NSString *str = [NSString stringWithFormat:#"%#", [NSDate date]];
NSLog(#"%#", str);
}
then it correctly prints out the current date. Obviously you would expect it to work in a non-ARC world, since str would be autoreleased and therefore valid until this method exits. However, in ARC-enabled code people generally consider the two forms (stringWithFormat & alloc/initWithFormat) to be equivalent.
So my question is whether code like the second example is guaranteed to work under ARC. That is, if I have a weak reference to an object that I get via what we would normally consider an autoreleasing convenience constructor, is it guaranteed to be safe to use that reference in the same scope I normally would have without ARC (i.e. until the method exits)?
The conventions of autoreleasing and allocing still apply in the world of ARC. The only difference is that ARC will insert extra retain/release calls to make it much harder to leak objects or access a dealloced object.
In this code:
__weak NSString *str = [[NSString alloc] initWithFormat:#"%#", [NSDate date]];
The only place the object is retained (or equivalent) is the alloc. ARC will automatically insert a release command, causing it to be immediately dealloced.
Meanwhile, in this code:
__weak NSString *str = [NSString stringWithFormat:#"%#", [NSDate date]];
By convention, the return value of a convenience constructor like this must be an autoreleased object*. That means the current autoreleasepool has retained the object and will not release it until the pool is drained. You are therefore all but guaranteed that this object will exist for at least the duration of your method - although you probably shouldn't rely on this behaviour.
(* or retained in some other way)
The lifetime of a local weak variable is not guaranteed at all. If the object that the variable points to is deallocated, the weak variable will point to nil afterwards.
If you have a weak reference to an object that you got via a method that does not return a retained object, it is not safe to assume that this object lives until the method exits. If you want to make sure that the object survives, use a strong reference.
Here is an example that shows that a non-retaining method's return value is not guaranteed to end up in the autorelease pool:
Create a new iOS project (Single View App using ARC and Storyboards)
Add this method to the AppDelegate.m:
+ (id)anObject
{
return [[NSObject alloc] init];
}
Replace -application:didFinishLaunchingWithOptions::
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
__weak id x = [AppDelegate anObject];
NSLog(#"%#", x);
return YES;
}
Important: Now set the Optimization level for Debug to -Os.
In this example, +[AppDelegate anObject] acts like a convenience constructor, but you will see (null) logged if you execute it on a device with -Os optimization. The reason for that is a nifty ARC optimization that prevents the overhead of adding the object to the autorelease pool.
You may have noticed that I switched to not using a library method like +[NSString stringWithFormat:]. These seem to always put objects in the autorelease pool, that may be for compatibility reasons.

Potential memory leak in NSData category

When using the XCode analyzer I get a message saying:
Potential leak of an object allocated
The code this is in my NSData(String) category, the code is:
- (NSString*) utf8String
{
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
Now how can I solve this? When I change the statement to:
- (NSString*) utf8String
{
return [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
}
My application crashes on the line where I call utf8String.
The cocoa naming conventions suggest that all methods return autoreleased objects, with the exception of methods whose names start with 'init', 'copy' or 'new'. The static analyzer knows and checks this.
You have two choices. You can rename the method to -newUTF8String, or you can return an autorelease object and retain it when you want to store the return value of this method.
I would prefer the latter, but both would be valid code.
I guess your application crashes because the variable is released before it is used. It is recommended to call retain if you do not use the return value right away but store it in a member variable.
...
myMemberVariable = [something utf8String];
[myMemberVariable retain];
...
To make sure that you do not produce a memory leak you have to release the member variable somewhere. A good place for that would be dealloc.
- (void)dealloc {
if (myMemberVariable) [myMemberVariable release];
[super dealloc];
}
I would also recommend having a look at Advanced Memory Management Programming Guide to get some detailed information about memory management of iOS.

Obj-c autorelease a variable up a chain of methods

I'm new to Obj-C and I have a question concerning the autorelease. Is it ok to return an autoreleased variable for several methods? For example:
- (void) methodC {
Object anObj = [self methodB];
//Do something with anObj
}
- (Object *) methodB {
return [self methodA];
}
- (Object *) methodA {
Object anObj = [[anObj alloc] init];
release [anObj autorelease];
}
Will the variable remain valid even if it is returned up a method chain and used at the top? Or does it have to be retained somewhere along the way?
thank you
Yes, it will be valid in this case. You only have to worry about the variable being deallocated if somebody drains the autorelease pool. As long as you've written every function that returns along the way and you don't explicitly drain the autorelease pool, you don't have to worry about objects being deallocated from under you.
In the vast majority of cases, the code in the NSRunLoop takes care of draining the autorelease pool. When you return control from your application code to the API code (such as by returning from a touchesBegan handler etc.), you don't know if the autorelease pool will be drained, so you have to assume in the worst case that it will. In that case, you have to retain any objects you want to keep references to.
For example:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Object *anObj = [self methodC]; // Your methodC as before -- anObj is valid
[pool drain]; // anObj will be deallocated here
The variable should remain valid. You only need to retain an object if it is actually "owned" by some other object and could be indirectly/unintentionally released along with it. For example, if you extracted an object from an array and then released the array, your object reference could become invalid unless you explicitly retain it.
For more details, see Object Ownership and Dismissal, particularly the sections on Autorelease and Validity of Shared Objects. The latter uses the following code to illustrate how you could "accidentally" make an object reference invalid.
heisenObject = [array objectAtIndex:n];
[array removeObjectAtIndex:n];
// heisenObject could now be invalid.
The following code shows how to mitigate this problem using retain.
heisenObject = [[array objectAtIndex:n] retain];
[array removeObjectAtIndex:n];
// use heisenObject.
[heisenObject release];

NSMutableString memory management get me confused

I am learning Objective-C right now, however, there is memory management puzzle here make me so confused.
Let me see, within one method, I create a NSMutableString, and return it.
- (NSMutableString *)methodNameWithParameter:(id)parameter
{
NSMutableString *string = [NSMutableString stringWithString:#""];
// do something
return string;
}
The question is who is responsible to release this memory, calling or called?
Second example:
- (NSMutableString *)methodNameWithParameter:(id)parameter
{
NSMutableString *string = [NSMutableString alloc]init] autorelease];
// do something
return string;
}
When memory has been released, it will be released at after return string;
or it will be released at call method and there is no reference to it.
The third one:
- (NSMutableString *)methodNameWithParameter:(id)parameter
{
NSMutableString *string = [NSMutableString alloc]init]];
// do something
return string;
}
This time the calling method need to release this memory, is that right?
If you follow the rule, you allocated memory then you are responsible to release it. 90% of time this will work. Of course there are some exception. But in general it should be good.
In your first example, you don't have to release it because you didn't allocate memory yourself, it's the stringWithString that is responsible (I believe it's doing an auto release)
In your second and third example, you are allocating memory with alloc, thus you have to release the memory once you are done with it.
In you second example, you are using autorelease, it means it the memory allocated will eventually be released. (similar to garbage collection in the Microsoft managed code world).