开发者

NSMutableArray, Adding / Removing objects?

开发者 https://www.devze.com 2022-12-20 23:17 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消