我的 iOS 应用程序中的内存管理存在一些问题。我加载一个 XML 并将该 XML 中的所有值设置为特定对象。现在我的问题是,当我每 15 - 20 次重新加载此 XML 时重新加载 XML,我的应用程序在解析时崩溃 这里是我的解析器的示例。
编辑:这是启用 NSZombie 时出现的错误,如果禁用 NSZombie,我没有收到错误消息。 -[CFNumber keep]:发送到已释放实例的消息
感谢您的帮助。
编辑:
我的代码的开头:
- (id)init
{
self = [super init];
if (self) {
TheObjects *theObjects = [[TheObjects alloc] init];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *theTmpObjects = [[TheObjects alloc] init];
[self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:@selector(finished:)]){
[delegate performSelector:@selector(finished:) withObject:theObjects];
}
if(reload)
[localTheTmpObjects release];
最佳答案
remove the line [localTheTmpObjects release]
you don't own the object
at the end, call the `[localTheTmpObjects autorelease];`
this is because if you release array, all its objects are released and hence may cause crash, when your array may in use
- (id)init
{
self = [super init];
if (self) {
TheObjects *obbjects = [[TheObjects alloc] init];
theObjects = objects;
[objects releas];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *obbjects = [[TheObjects alloc] init];
thetmpObjects = objects;
[objects releas]; [self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:@selector(finished:)]){
[delegate performSelector:@selector(finished:) withObject:theObjects];
}
}
关于iphone - iOS 编程中的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10484464/