【发布时间】:2010-10-10 05:12:05
【问题描述】:
我几乎理解了 Objective-C 中的简单引用计数/内存管理,但是我在使用以下代码时遇到了困难。我正在发布 mutableDict(在下面的代码中注释),它在我的代码中造成了有害行为。如果我让内存泄漏,它会按预期工作,但这显然不是这里的答案。 ;-) 你们中的任何一个更有经验的人会不会善意地指出我正确的方向,因为我可以重新编写任何这种方法来更好地处理我的内存占用?主要是我如何管理 NSMutableDictionary *mutableDict,因为这是这里的罪魁祸首。我想了解这个问题,而不仅仅是复制/粘贴代码——所以一些 cmets/feedback 是理想的。谢谢大家。
- (NSArray *)createArrayWithDictionaries:(NSString *)xmlDocument
withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *mutableArray = [[[NSMutableArray alloc] init] autorelease];
//NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
CXMLDocument *theXMLDocument = [[[CXMLDocument alloc] initWithXMLString:xmlDocument options:0 error:&theError] retain];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
int i, j, cnt = [nodes count];
for(i=0; i < cnt; i++) {
CXMLElement *xmlElement = [nodes objectAtIndex:i];
if(nil != xmlElement) {
NSArray *attributes = [NSArray array];
attributes = [xmlElement attributes];
int attrCnt = [attributes count];
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
for(j = 0; j < attrCnt; j++) {
if([[[attributes objectAtIndex:j] name] isKindOfClass:[NSString class]])
[mutableDict setValue:[[attributes objectAtIndex:j] stringValue] forKey:[[attributes objectAtIndex:j] name]];
else
continue;
}
if(nil != mutableDict) {
[mutableArray addObject:mutableDict];
}
[mutableDict release]; // This is causing bad things to happen.
}
}
return (NSArray *)mutableArray;
}
【问题讨论】:
标签: ios objective-c iphone cocoa cocoa-touch