views:

111

answers:

2

Is this the correct way to pop objects off the front of an array. I was just curious as I was thinking there might be a method for NSMutableArray that returned a retained object. Just curious if I am getting this right?

// PUTTING OBJECTS IN
NSMutableArray *fgStore = [[NSMutableArray alloc] init];
for(int counter=1; counter<=5; counter++) {
    NSString *dataValue = [[NSString alloc] initWithFormat:@"DATA%d", counter];
    [fgStore addObject:dataValue];
    [dataValue release];
}

// TAKING OBJECTS OUT
NSString *saveMe = [[fgStore objectAtIndex:0] retain];
[fgStore removeObjectAtIndex:0];    
NSLog(@"SAVE: %@", saveMe);
...
...
[fgStore release];
[saveMe release];

gary

+2  A: 

This is exactly the way I would do it, I don’t think there’s another. By returning a retained object you would break one of the main rules of Cocoa memory management: Most of the time you only own the objects returned by init… methods and have to retain the rest.

zoul
+1  A: 

That code looks fine. The only thing you might want to keep in mind is that you can use autorelease to avoid the explicit releases when you're done. For instance:

for(int counter=1; counter<=5; counter++) {
    NSString *dataValue = [[[NSString alloc]
                             initWithFormat:@"DATA%d", counter] autorelease];
    [fgStore addObject:dataValue];
}

I don't believe there is any NSMutableArray method that returns a retained object. Remember that methods which return retained values have names which start with alloc, new, or copy.

nall
Some people would frown on the autorelease, as they only use autoreleasing when necessary. (A matter of style, I guess.) Also, `NSString` has a convenience `stringWithFormat` class method, so that the `alloc` and `autorelease` pair is extra, but that’s nitpicking.
zoul
Yeah, good point about the NSString convenience method. That would make for the most readable code.
nall
Thank you both, I was going for explicit release because I am working on the iPhone and I want to make sure that I manually free things to keep my memory footprint as low as I can. (i.e. not waiting for the autorelease pool to be drained) that was my reasoning anyways ...
fuzzygoat
Autoreleased objects are usually collected with the next runloop iteration, which means almost immediately. You don’t have to fear them unless you allocate *a lot* of memory in a loop. (I also code exclusively for the iPhone and use autoreleased objects even in games without scruples.) But I also opt for the explicit release, unless I already have an autoreleased object.
zoul
Thank you, I am only just starting out, so I have been trying to stay with the best practice way of working. Like you said, I nearly always use an explicit release, although sometimes you have to go with what you get back from a method.
fuzzygoat