objective c memory management in for loops - objective-c

I want to execute a for loop that looks like this:
for (id object in [[MyClass methodReturningSet] allObjects]) {
//do something
}
that methodReturningSet looks something like this:
- (NSSet *)methodReturningSet {
MyObject *object1 = [[MyObject alloc] initWithCustomInfo:info1] autorelease];
MyObject *object2 = [[MyObject alloc] initWithCustomInfo:info2] autorelease];
MyObject *object3 = [[MyObject alloc] initWithCustomInfo:info3] autorelease];
MyObject *object4 = [[MyObject alloc] initWithCustomInfo:info4] autorelease];
return [NSSet setWithObjects: object1, object2, object3, object4, nil];
}
My question, is this safe in terms of memory management?
My current understanding is that 'object' will be sent a release message after the completion of the run loop.
My first question is, does the entire for loop execute within one single run loop?
My second question is, does it matter if the objects get sent release messages via the autorelease pool since the array we're looping over holds a strong reference to all the objects it contains?
hope that was clear . . . any thoughts?

My first question is, does the entire for loop execute within one
single run loop?
Yes.
My second question is, does it matter if the objects get sent release
messages via the autorelease pool since the array we're looping over
holds a strong reference to all the objects it contains?
The NSSet will retain the objects you pass to it. After adding the objects to it, you can release your own references if you don't need them anymore. This can either be normal release calls after adding them to the set (see below), or autorelease calls, as you did it. When you release the NSSet, it will also release (and in this case dealloc) all its objects.
You could use normal release messages to like this:
- (NSSet *)methodReturningSet {
MyObject *object1 = [[MyObject alloc] initWithCustomInfo:info1];
MyObject *object2 = [[MyObject alloc] initWithCustomInfo:info2];
MyObject *object3 = [[MyObject alloc] initWithCustomInfo:info3];
MyObject *object4 = [[MyObject alloc] initWithCustomInfo:info4];
NSSet *set = [NSSet setWithObjects: object1, object2, object3, object4, nil];
[object1 release];
[object2 release];
[object3 release];
[object4 release];
return set;
}
That being said, consider using Automatic Reference Counting (ARC).

My first question is, does the entire for loop execute within one single run loop?
yes.
My second question is, does it matter if the objects get sent release messages via the autorelease pool since the array we're looping over holds a strong reference to all the objects it contains?
Using autorelease or releasing the objects explicitly will not make any difference, since as you say they are also retained by the NSSet object; so the will live for the whole duration of the for loop and get released when the autoreleased NSSet returned through methodReturningSet is deallocated.
You might possibly sightly improve things if you do not autorelease that NSSet and release it explicitly just outside of the loop (but this will only make a difference if you do not immediately return after leaving the loop).

Related

When to use Self?

I am new to iOS development.
I have property as follows,
#property(nonatomic,retain)NSMutableArray *dataArray;
I am doing the following, to alloc it
self.dataArray=[[NSMutable alloc]init];
In the dealloc I am doing the following
-(void)delloc{
[dataArray release];
[super dealloc];
}
But I am getting memory leak for my array initialization.However , it doesn't create the
leak when I don't use self. But I wonder is it a write approach to initialise the array
without using self. Any help is appreciated.
You're getting a leak because the dataArray property is declared with retain, which means that when you use self (thus you use the setter), your retain count goes up to 2 and you only release it once. On the other hand, if you only use the ivar, the retain count is 1 (because of alloc) and you release it once, which is fine. To avoid the memory leak in the first situation, autorelease it like this.
self.data = [[NSMutableArray alloc] init] autorelease];
That will balance the retain count. As for access, except for inside the dealloc method, try to use self (setter and getter)
You should read the memory management docs, first thing to start with when developing for Cocoa Touch.
Also, why don't you use ARC?
If you use the self. signature you are accessing to the object via automatically generated / custom getter/setter. The setter will tipically manage the memory and you don't need to do that.
If you don't use self you access directly to the object.
The code what you presented is leaking, because the default setter of the dataArray will retain to the array, what you set with self.dataArray = [[NSMutableArray alloc] init];
The correct usage is:
self.dataArray = [[[NSMutableArray alloc] init] autorelease];
or:
_dataArray = [[NSMutableArray alloc] init];
What's happening here is that alloc is adding one to the retain count of the new object. The property reference is also retaining the object. If you want to do it this way, you only want one of those. A common method is:
self.dataArray = [[[NSMutableArray alloc]init] autorelease];
However, better still is to use ARC as #c.cam108 suggested and avoid the whole problem.

Alloc a new objective C object to a retained property?

Sorry for asking a totally basic question, but if I have a synthesized property that is retained.
self.myProperty = [[NSObject alloc] init];
will cause a memory leak?
So am I correct in thinking that I need to do
self.myProperty = [[NSObject alloc] init];
[self.myProperty release];
in order to balance? Because that seems dumb.
Standard practice would be to use autorelease in that situation. So:
self.myProperty = [[[NSObject alloc] init] autorelease];
This is because init returns a retained object, and since your property also retains it, you'll have to release it.
Edited to add: #walkytalky makes a good point in the comments that it is actually alloc that retains the object, init just returns it.
Here is a thread that you will find helpful.
You are correct. Without ARC, any property that is retained needs to be released as well.
You can also do:
self.myProperty = nil;
From the docs:
retain
Specifies that retain should be invoked on the object upon
assignment.
The previous value is sent a release message.
Another (more verbose) technique is to do:
NSObject *o = [[NSObject alloc] init]; //retain count 1
self.myProperty = o; //retain count 2
[o release]; //retain count 1
Personally though, I'd probably just use autorelease as in the first example above.
With ARC enabled, xcode will handle alle the memory management.
When not using ARC be sure to release it in the dealloc method.

Why Do I Have to Create An Object and Assign It to A Property in Objective C?

So I had this code, and it did not work:
for (NSDictionary *item in data){
[self.resultsArray addObject:item];
}
self.resultsArray is nil. But then I changed it to this:
NSMutableArray *myDataArray = [[NSMutableArray alloc] init];
for (NSDictionary *item in data){
[myDataArray addObject:item];
}
self.resultsArray = myDataArray;
[myDataArray release];
and now it worked. self.resultsArray is now populated
So I'm a beginner in Objective C and I was wondering why can I not just directly use it in the property's addObject. Why did I have to create another mutable array, populate it, assign it to the resultsArray property and release the mutable array I made?
Thanks in advance!
EDIT: Also, in a lot of books I've been working on, this is done a lot.
simple answer
You didn't initialize self.resultArray before adding objects to it. It is just a pointer to the value which is nil until you alloc it.
self.resultArray = [[NSMutableArray alloc] init]; before adding objects to it will solve the issue.
However, this way of alloc'ing will create a memory leak, therefore it is not shown in books and examples. Memory leak can happen if the self.resultArray property is marked as retain and by calling alloc it will be retained 2 times.
If self.resultsArray is nil, then [self.resultsArray addObject:item] will NOT add an object to the array, it will just do nothing (because the array will be nil by default, and sending messages to nil is a no-op in Objective-C). When you create a mutable array as a local variable, you can add things to it — then if you assign it to the property, well, everything works as you expect and self.resultsArray will no longer be nil.
Typically when you have properties like this, you'd set them up in your init method:
- (id)init {
// ...
self.resultsArray = [NSMutableArray array];
// or access the ivar directly:
// _resultsArray = [[NSMutableArray alloc] init];
// ...
}
Then as soon as your object is initialized you'll be able to add things to the array. Again, if you don't do this, it will be nil by default, and [self.resultsArray addObject:item] will have no effect.
Chances are you are not initializing the array (I'm going to assume myDataArray is an NSMutableArray).
In your init method, call myDataArray = [NSMutableArray array]; and it'll work
The important thing to note is that you're not creating another mutable array as you didn't have an array to start with. Merely declaring a property or variable does not create an object to go along with it. That's why self.resultsArray starts out as nil.
The working code you have is designed to allow you to explicitly release the array as you are retaining it twice: once when you alloc it and once when you assign it to your property. You only want one of those retains, so you release once.
You could just do:
self.resultsArray = [[NSMutableArray alloc] init];
[self.resultsArray release];
for (NSDictionary *item in data){
[self.resultsArray addObject:item];
}
This is less code, but it's not as clear. Clarity is important.

simple NSMutable array question

umm So simple question here:
I have an instance of NSMutableArray declared in my header
NSMutableArray *day19;
#property (nonatomic, retain) NSMutableArray *day19
implementation:
#synthesize day19;
In my viewDidLoad
self.day19 = [[NSMutableArray alloc] init];
In the myMethod where I want to add objects to the array I:
NSObject *newObject = [[NSObject alloc] init];
[day19 addObject:newObject];
However... when i check the day19 array there is nothing in it. If I conversely add the newObject to a tempArray within the myMethod scope and then set the day19 array to the tempArray, day19 has the objects.
Super basic I know just must be a confused morning or something...
thanks for any help
Is day19 actually an instance variable? In the snippet, it's not clear when it's declared as an instance variable or just as a variable outside the scope of the class.
A couple of things:
Are you sure viewDidLoad is the right place to init your array? Confer here.
Also, at least from the code you've got posted, it looks like you're being sloppy with your retains. If your property is a retain type, you should not be writing:
self.myProperty = [[Something alloc] init]; // double retain here, bad
You should instead be writing something like:
self.myProperty = [[[Something alloc] init] autorelease]; // single, good
Also, with
NSObject *newObject = [[NSObject alloc] init];
[day19 addObject:newObject];
unless you have a
[newObject release];
down the pike, you've got a memory leak.
In my viewDidLoad
self.day19 = [[NSMutableArray alloc] init];
In the myMethod where I want to add objects to the array I:
NSObject *newObject = [[NSObject alloc] init];
[day19 addObject:newObject];
However... when i check the day19 array there is nothing in it. If I conversely add the newObject to a tempArray within the myMethod scope and then set the day19 array to the tempArray, day19 has the objects.
Let me guess: You checked the array with code like this:
NSLog(#"day19 contains %lu objects", [day19 count]);
Remember that a message to nil does nothing and returns nil, 0, or 0.0. That's why the output said 0 objects: You don't have an array in the first place. The most probable reason for that is that viewDidLoad hasn't been called yet, so you have not yet created the mutable array.
It's also possible that you have an array (i.e., the view has been loaded) at the time you examine the array, but you didn't have an array yet (the view hadn't been loaded yet) at the time you tried to add to the array, so your addObject: message fell on deaf ears.
Consider creating the array earlier. You probably should be creating it in init or initWithCoder:.
A third possibility is that you examined the array before you ever added to it. Make sure you log or break at both points, so you know which one happened first.
Whatever the problem is, you also need to either assign the array to the instance variable, not the property, or autorelease the array before assigning it to the property. Otherwise, you're over-retaining the array, which means you will probably leak it later on. You probably need to review the Memory Management Programming Guide for Cocoa.

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.