我想填充这样的数组:
NSMutableArray *array = [self methodThatReturnsAnArray];
在“methodThatReturnsAnArray”方法中,我创建了一个这样的数组:
NSMutableArray *arrayInMethod = [[NSMutableArray alloc] init];
当我完成填充“arrayInMethod”时,我正在返回数组,以防止我正在使用的内存泄漏:
return [arrayInMethod autorelease];
但是从未填充“数组”变量。删除“自动释放”时它工作正常。我该怎么做才能确保我发布了返回的对象?
修改
+ (NSMutableArray *)buildInstants:(NSArray *)huntsArray {
NSMutableArray *goGetObjects = [[[NSMutableArray alloc] init] autorelease];
for (int i = 0; i < [huntsArray count]; i++) {
NSDictionary *huntDict = [huntsArray objectAtIndex:i];
PHGoGet *goGet = [[PHGoGet alloc] init];
goGet.title = [huntDict objectForKey:@"title"];
goGet.description = [huntDict objectForKey:@"description"];
goGet.start = [huntDict objectForKey:@"start"];
goGet.end = [huntDict objectForKey:@"end"];
goGet.ident = [huntDict objectForKey:@"id"];
if ((CFNullRef)[huntDict objectForKey:@"image_url"] != kCFNull) {
goGet.imageURL = [huntDict objectForKey:@"image_url"];
} else {
goGet.imageURL = nil;
}
if ((CFNullRef)[huntDict objectForKey:@"icon_url"] != kCFNull) {
goGet.iconURL = [huntDict objectForKey:@"icon_url"];
} else {
goGet.iconURL = nil;
}
goGet.longitude = [huntDict objectForKey:@"lng"];
goGet.latitude = [huntDict objectForKey:@"lat"];
goGet.companyIdent = [huntDict objectForKey:@"company_id"];
[goGetObjects insertObject:goGet atIndex:i];
[goGet release];
}
return [[goGetObjects copy] autorelease];
}
答案 0 :(得分:1)
尝试使用NSMutableArray
的便捷方法...更改:
NSMutableArray *arrayInMethod = [[NSMutableArray alloc] init];
要...
NSMutableArray *arrayInMethod = [NSMutableArray array];
array
将返回一个自动释放对象。
答案 1 :(得分:1)
首先,我建议您不要从任何方法返回NSMutableArray。最好使用NSArray来避免一些非常难以调试的问题。我的主张是:
您声明了可变数组并填充它:
NSMutableArray *arrayInMethod = [[[NSMutableArray alloc] init] autorelease];
然后你返回一个自动释放的副本:
return [[arrayInMethod copy] autorelease];
最后,当您获取返回的数组时,再次使其变为可变(仅当您需要更改它时):
NSMutableArray *array = [[self methodThatReturnsAnArray] mutableCopy];
完成数组后,将其释放:
[array release];