简体   繁体   中英

NSMutableArray, Adding / Removing objects?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM