Releasing With NSMutableArray? - objective-c

I am allocating myMDD in main which contains an NSMutableArray instance variable (alloc/init-ed in init). When I add items to the NSMutableArray (frameList) I release after adding. The array and the objects it now contains are released at the bottom of main.
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
MDD *myMDD = [[MDD alloc] init];
Frame *myFrame = [[Frame alloc] init];
[myMDD addFrame:myFrame];
[myMDD release];
[pool drain];
return 0;
}
// METHOD_ mdd addFrame:
-(void)addFrame:(Frame*) inFrame {
[frameList addObject:inFrame];
[inFrame release];
}
// METHOD_ mdd dealloc
-(void)dealloc {
NSLog(#"_deal...: %#", self);
[frameList release];
[super dealloc];
}
My question is that the "static analyser" reports a potential memory leak, prefering to have the release for frame added main. (i.e)
int main (int argc, const char * argv[]) {
...
[myFrame release]; // Added
[myMDD release];
[pool drain];
return 0;
}
// METHOD_ mdd addFrame:
-(void)addFrame:(Frame*) inFrame {
[frameList addObject:inFrame];
// [inFrame release];
}
I can see why this is, if I alloc myMDD and never call addFrame then I need to release it. Maybe its just a case of adding a autorelease to myMDD, but would that work in the situation where I call addFrame and the NSMutableArray is releasing the object?
EDIT_001
Changed to ...
int main (int argc, const char * argv[]) {
...
[myMDD addFrame:myFrame];
[myFrame release];
myFrame = nil;
[myMDD release];
[pool drain];
return 0;
}
// METHOD_ mdd addFrame:
-(void)addFrame:(Frame*) inFrame {
[frameList addObject:inFrame];
}
gary

The reason you got that warning is because an NSMutableDArray retains any object put into it; likewise, when an NSMutableArray is released, it also releases any object contained within it. So let's look at your code.
This line:
Frame *myFrame = [[Frame alloc] init];
creates a new instance of Frame called myFrame. myFrame has a retain count of 1, because you used alloc/init to create it.
You then pass this to addFrame::
[myMDD addFrame:myFrame];
Which in turn puts it into an instance of an NSMutableArray:
[frameList addObject:inFrame];
At this point, inFrame and myFrame point to the same object. When added to the array, this object's retain count is incremented, so now it is 2.
Later on, back in main, you release myMDD, which releases frameList. Assuming frameList now has a retain count of 0, it is deallocated -- and, as an NSMutableArray, it releases any object it contains, which includes the object pointed to my myFrame.
So now myFrame's retain count is 1...so it doesn't get released, and you have a memory leak.
One Cocoa-y way to solve the problem is by autorelease myFrame:
Frame *myFrame = [[[Frame alloc] init] autorelease];
Which means it won't leak. Then, use the -[MDD dealloc] method in your second example (Edit_001). You're right that you shouldn't release inFrame in your addFrame method, since you're not retaining it.

As per convention, an add method should just retain the object if needed, not release it. And as a general rule, you should not release object that you did not retain, in your example the scope where you retained (created) the frame is not the same as in the addFrame method.
By scope I mean logic scope, not language scope.
In that particular example, you must call release just after addFrame. But the release should not be in the addFrame method.

In most cases, Cocoa provides class methods that initialize and return an autoreleased version of an object. i.e. [NSMutableDictionary dictionary] vs [[NSMutableDictionary alloc] init].
I advise to always use the class methods where possible if you're creating an object that you won't need to keep around or if you going to store it in a collection (NSArray, NSDictionary, NSSet, etc).
The general rule then is to only alloc objects your class owns directly (i.e. an instace or class variable, not inside a collection) and to use the class methods for all other cases.

Related

Clarifications needed for a crash using NSArray, blocks and Manual Reference Counting

I need some clarifications on a crash I'm encountering using NSArray, blocks and Manual Reference Counting. My goal is to store blocks on a collection (NSArray in this case) in order to reuse them in the future.
I've setup a small sample to replicate the issue. In particular, I have a class Item that looks like the following:
#import <Foundation/Foundation.h>
typedef void(^MyBlock)();
#interface Item : NSObject
- (instancetype)initWithBlocks:(NSArray*)blocks;
#end
#import "Item.h"
#interface Item ()
#property (nonatomic, strong) NSArray *blocks;
#end
#implementation Item
- (instancetype)initWithBlocks:(NSArray*)blocks
{
self = [super init];
if (self) {
NSMutableArray *temp = [NSMutableArray array];
for (MyBlock block in blocks) {
[temp addObject:[[block copy] autorelease]];
}
_blocks = [temp copy];
}
return self;
}
The usage is described below (I'm using in the app delegate).
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
__block typeof(self) weakSelf = self;
MyBlock myBlock1 = ^() {
[weakSelf doSomething1];
};
MyBlock myBlock2 = ^() {
[weakSelf doSomething1];
};
NSArray *blocks = #[myBlock1, myBlock2];
// As MartinR suggested the code crashes even
// if the following line is commented
Item *item = [[Item alloc] initWithBlocks:blocks];
}
If I run the app, it crashes with an EXC_BAD_INSTRUCTION (note that I've already enabled All Exceptions breakpoints). In particular, the app stops in the main.
int main(int argc, const char * argv[]) {
return NSApplicationMain(argc, argv);
}
Note: As suggested by Ken Thomases, if you use bt command on llvm console, you are to see the back trace. In this case it shows the following:
-[__NSArrayI dealloc]
If I comment the [weakSelf doSomethingX]; it works without crashes (it does not mean that is correct).
Modifying the code a little bit like the following, all runs ok.
// Item does not do anymore the copy/autorelease dance
// since used in the declaration of the blocks
- (instancetype)initWithBlocks:(NSArray*)blocks
{
self = [super init];
if (self) {
_blocks = [blocks retain];
}
return self;
}
and
__block typeof(self) weakSelf = self;
MyBlock myBlock1 = [[^() {
[weakSelf doSomething1];
} copy] autorelease];
MyBlock myBlock2 = [[^() {
[weakSelf doSomething1];
} copy] autorelease];
NSArray *blocks = #[myBlock1, myBlock2];
Item *item = [[Item alloc] initWithBlocks:blocks];
What is the point here? I think I'm missing something but I don't know what.
Update 1
Ok. I'll try to recap my thoughts based on the comments with #Martin R and #Ken Thomases.
A block, by default, is created on stack if a copy message is not sent to it (ARC does this for us) in order to move it on the heap. So, the situation in this case is the following. I create an autorelease array and I add two blocks where retain is called in a implicit manner. When the applicationDidFinishLaunching method finishes is execution, the blocks, since created on the stack (they are automatic variables) disappear. In a later moment, the array called blocks will be released since has been marked as autorelease. So, it will crash since it will send a release object to blocks that do not exist anymore.
So, my question is the following: What does it mean to send a retain message to a block that is on the stack? Why the array is the source of the crash (see the back trace)? In other words, since a block is on the stack, will it bump the retain count of it? And when it goes out of scope? In addiction, why if I comment the [weakSelf doSomething1] line the code works without problems? Not very clear to me this part.
You are sticking an object from the stack into an autoreleased array. BOOM ensues.
Consider:
typedef void(^MyBlock)();
int main(int argc, char *argv[]) {
#autoreleasepool {
NSObject *o = [NSObject new];
MyBlock myBlock1 = ^() {
[o doSomething1];
};
NSLog(#"o %p", o);
NSLog(#"b %p", myBlock1);
NSLog(#"b retain %p", [myBlock1 retain]);
NSLog(#"b copy %p", [myBlock1 copy]);
NSLog(#"s %p", ^{});
sleep(1000000);
}
}
Compiled/run as -i386 (because the #s are smaller and more obvious):
a.out[11729:555819] o 0x7b6510f0
a.out[11729:555819] b 0xbff2dc30
a.out[11729:555819] b retain 0xbff2dc30
a.out[11729:555819] b copy 0x7b6511a0
a.out[11748:572916] s 0x67048
Since the object is at 0x7b, we can assume that is the heap. 0xb is really high memory and, thus, the stack.
The retain doesn't cause a copy (because doing so would have invariably led to leaks) and retain on a stack based object is meaningless.
If you change the [o doSomething1]; to [nil doSomething1]; then that becomes a static block and that lives in readonly mapped memory (readonly-executable pages from the mach-o's TEXT segment) and, thus, there is no allocation to deallocate and retain/release/autorelease are no-ops.
As you can see, the static block ended up around 0x67048 (this number may change from run to run, btw, for a variety of reasons. Low in memory.
In fact, because of the sleep(), we can run vmmap against the a.out process and see:
==== Writable regions for process 11772
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
__DATA 00067000-00068000 [ 4K] rw-/rwx SM=ZER /tmp/a.out
That is, the static block was in the first 4K segment of mapped writable regions from the mach-o file. Note that this doesn't mean the code is in that writable region (SECURITY HOLE if it were). The code is in the TEXT segment mapped into the readable regions.

Memory leak caused by alloc in Class Method?

I have found that if I alloc a new object inside a Class method and return it to main() it seems to cause a memory leak when I no longer want the object.
For example, here is a simple Class that includes a Class method that returns an instance of itself:
#interface Stinker : NSObject
{
int a;
}
+(instancetype) makeAStink;
-(void) showThem;
-(void) setEm: (int) z;
#end
#implementation Stinker
-(void) showThem
{
NSLog(#"%d",a);
}
-(void) setEm: (int) z
{
a = z;
}
-(void) dealloc
{
NSLog(#"Arrrgggggh!");
}
+(instancetype) makeAStink
{
id temp = [[self alloc] init];
return temp;
}
#end
Now if I create an instance directly from main():
Stinker *aStink =[[self alloc] init];
and subsequently set aStink to nil:
aStink = nil;
the overridden dealloc method is called and the Argggggh! message is logged. That's fine and as expected.
But if I use the Class method I wrote to create an instance:
Stinker *aNewStink = [Stinker makeAStink];
the behaviour is different.
Now if I set aNewStink to nil, it will no longer point to the object but the object is not destroyed. dealloc is not called and the Arggggh message is not logged.
It seems like it still has an owner somewhere.
Of course when main() terminates the object is destroyed and dealloc is eventually called.
But this seems to suggest that unused and unloved objects are still hanging around on the heap until the program terminates.
Isn't this a memory leak?
Should I just avoid using Class methods to alloc new instances?
When using ARC, the following code
+(instancetype) makeAStink
{
id temp = [[self alloc] init];
return temp;
}
will be same with Non-ARC like this:
+(instancetype) makeAStink
{
id temp = [[self alloc] init];
return [temp autorelease];
}
Thanks to autorelease, aNewStink = nil will make aNewStink do release in next runloop.
So if you do this:
#autoreleasepool {
Stinker *aNewStink = [Stinker makeAStink];
aNewStink = nil;
}
Dealloc method is called immediately.
this is MRC (without ARC) code for your example
+(instancetype) makeAStink
{
id temp = [[self alloc] init];
return [temp autorelease];
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id obj = [Stinker makeAStink]; // obj is autoreleased object
id obj2 = [[Stinker alloc] init]; // obj2 is not autoreleased
[obj2 release]; // so you need to release it
[pool release]; // now obj is released and deallocated
so obj have an extra retain count which will be released (and deallocated) in next runloop whereas obj2 will be released immediately when release is called
this is not memory leak, it is usual behaviour and (normally) doesn't affect program performance in noticeable way

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.

dealloc method is not invoked when set an object to nil

I have a question.
I first created an object which extends NSObject, I provided overrides for the description and dealloc methods. Here's my Employee.m file:
#implementation Employee
.....
-(NSString *)description
{
return [NSString stringWithFormat:#"Employ ID: %d has $%d value of assets", [self employeeID], [self valueOfAssets]];
}
-(void)dealloc
{
NSLog(#"deallocating.. %#", self);
[super dealloc];
}
In my main.m, I first created an NSMutableArray to hold a list of Employee objects:
NSMutableArray *employees = [[NSMutableArray alloc] init];
for (int i =0; i< 10; i++)
{
// Create an instance of Employee
Employee *person = [[Employee alloc] init];
// Give the instance varaible interesting values
[person setEmployeeID:i];
[employees addObject: person];
}
and at the end I set employees to nil
employees = nil;
I expected the dealloc method of each Employee object to be called and I would see some logs like:
deallocating.. Employ ID 0 has value.....
deallocating.. Employ ID 2 has value.....
....
However, I didn't see any logs and if I set a breakpoint on the dealloc method, the breakpoint is never hit.
Any thoughts?
A couple of observations:
person = nil does not release an object in non-ARC code. It will in ARC code (at least if it's strong).
In ARC, local objects will be released for you automatically when they fall out of scope. In non-ARC, objects falling out of scope will not be released for you (and if you don't have other references to those objects elsewhere, you'll end up with a leak).
Adding an item to a mutable array will increase the retain count of the item, so even if you include a release in your non-ARC code, the object won't be released until the retain count drops to zero (accomplished by not only releasing the person objects after you add them to the array, but also removing them from the array.
Thus, given that this is non-ARC code, it could be something like:
- (void)testInNonArcCode
{
NSMutableArray *employees = [[NSMutableArray alloc] init]; // employees retain count = +1
for (int i =0; i< 10; i++)
{
//create an instance of Employee
Employee *person = [[Employee alloc] init]; // person retain count = +1
//Give the instance varaible interesting values
[person setEmployeeID:i];
[employees addObject: person]; // person retain count = +2
[person release]; // person retain count = +1 (YOU REALLY WANT TO DO THIS OR ELSE OR NON-ARC PROGRAM WILL LEAK)
// person = nil; // this does nothing, except clears the local var that's limited to the for loop scope ... it does nothing to reduce the retain count or improve memory management in non-ARC code, thus I have commented it out
}
// do whatever you want
[employees removeAllObjects]; // this will remove all of the person objects and they will have their respective retain counts reduced to 0, and therefore the Employee objects will be released
[employees release]; // employees array's own retain count reduced to zero (and will now be dealloced, itself)
}
In ARC code:
- (void)testInArcCode
{
NSMutableArray *employees = [[NSMutableArray alloc] init]; // employees retain count = +1
for (int i =0; i< 10; i++)
{
//create an instance of Employee
Employee *person = [[Employee alloc] init]; // person retain count = +1
//Give the instance varaible interesting values
[person setEmployeeID:i];
[employees addObject: person]; // person retain count = +2
// person = nil; // this would reduce person retain count to +1 (but unnecessary in ARC because when person falls out of scope, it will have it's retain count automatically reduced)
}
// do whatever you want
[employees removeAllObjects]; // this will remove all of the person objects and they will have their respective retain counts reduced to 0, and therefore will be released
// [employees release]; // not permitted in ARC
// employees = nil; // this would effectively release employees, but again, not needed, because when it falls out of scope, it will be released anyway
}
The proper way of freeing objects is to do
[employees release];
Setting it to nil will not release the memory.
By virtue of you being allowed to call [super dealloc], I can assume that you are not using Automatic Reference Counting. This means that you need to explicitly pair every alloc you write with a balancing release call. For you, when you make the array nil, you essentially leaked all of the memory for the employees. You need to loop over the array again to release them all, or better yet since you are learning... Start as soon as possible writing ARC code.
It may be important to note that ARC was created for exactly this kind of situation; it makes sense to our brains, and now it can be a reality if you use the latest tools.

Objective-C Properties and Memory Management

Given the following property definition:
#property (nonatomic,retain) MyObject* foo;
does the following code cause a memory leak:
self.foo = [[MyObject alloc] init];
?
It looks like the alloc call increments the retain count on the object to 1, then the retain inside the property setter increases it to 1. But since the initial count is never decremented to 0, the object will stick around even when self is released. Is that analysis correct?
If so, it looks like I have two alternatives:
self.foo = [[[MyObject alloc] init] autorelease];
which is not recommended on the iPhone for performance reasons, or:
MyObject* x = [[MyObject alloc] init];
self.foo = x
[x release];
which is a bit cumbersome. Are there other alternatives?
Are there any alternatives?
No.
You are not going to be able write much of an iPhone application without using autorelease and the Cocoa Touch library uses them in many places. Understand what it's doing (adding the pointer to a list for removal on the next frame) and avoid using it in tight loops.
You can use class method on MyObject that does alloc/init/autorelease for you to clean it up.
+ (MyObject *)object {
return [[[MyObject alloc] init] autorelease];
}
self.foo = [MyObject object];
The easiest way to manage a retained property on the iPhone is the following (autorelease is not as bad as you think, at least for most uses):
-(id)init {
if (self = [super init]) {
self.someObject = [[[Object alloc] init] autorelease];
}
return self;
}
-(void)dealloc {
[someObject release];
[super dealloc];
}
The autorelease releases the reference to the floating instance which is assigned to self.object which retains its own reference, leaving you with the one reference you need (someObject). Then when the class is destroyed the only remaining reference is released, destroying the object.
As described in another answer, you can also create one or more "constructor" messages to create and autorelease the objects with optional parameters.
+(Object)object;
+(Object)objectWithCount:(int)count;
+(Object)objectFromFile:(NSString *)path;
One could define these as:
// No need to release o if fails because its already autoreleased
+(Object)objectFromFile:(NSString *)path {
Object *o = [[[Object alloc] init] autorelease];
if (![o loadFromFile:path]) {
return nil;
}
return o;
}
You are right, self.foo = [[MyObject alloc] init]; is leaking memory. Both alternatives are correct and can be used. Regarding the autorelease in such a statement: keep in mind that the object will released by the autorelease pool as soon as the current run loop ends, but it will most probably be retained a lot longer by self, so there is no issue with memory usage spikes here.