简体   繁体   English

NSMutableArray,添加/删除对象?

[英]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. 我只是好奇,因为我在想可能有一个NSMutableArray方法可以返回保留的对象。 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. 通过返回保留的对象,您将破坏Cocoa内存管理的主要规则之一:大多数时候,您仅拥有由init…方法返回的对象,而必须保留其余部分。

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. 我不相信有任何NSMutableArray方法返回保留的对象。 Remember that methods which return retained values have names which start with alloc, new, or copy. 请记住,返回保留值的方法的名称以alloc,new或copy开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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