核心数据和内存泄漏

时间:2011-02-08 20:47:20

标签: iphone objective-c memory-leaks

我正在使用Core Data,将一些数据提取到NSArray中,然后通过它循环。

    ......
    NSMutableArray *persons = [[NSMutableArray alloc] init];
NSError *error;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person"   inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *info in fetchedObjects) {

        ToggleButtonInfo *btn = [[ToggleButtonInfo alloc] init];

        btn.buttonName = [info valueForKey:@"name"];

        [persons addObject:btn];
    }        
    [fetchRequest release];

    return persons;

然后我将人员发送到呈现按钮的组件。在乐器中我得到了内存泄漏 enter image description here

如果我将 btn.buttonName = [info valueForKey:@“name”]; 替换为 btn.buttonName = @“其他东西”; 泄密绝望。请注意NSSQLCore。每次调用此方法刷新视图时,泄漏都会增加。我想提一下“Person”表与另一个表的关系,一对多。在组件中,当我即将加载新数据时,我发布了NSMutableArray,它看起来不是问题。我应该在这里发布其他东西吗?我错过了什么?

更新******************************************* 这是仪器的截图。看起来自定义对象是正确发布的。问题与核心数据有关,不是吗? enter image description here ..并进入NSString: enter image description here

4 个答案:

答案 0 :(得分:3)

最基本的内存泄漏是不平衡的保留。从获取对象的位置几乎与它在活着时使用的对象无关。

根据您共享的代码,我最好的猜测是,ToggleButtonInfo会过度保留buttonName属性。您应该仔细研究ToggleButtonInfo的buttonName属性的生命周期。你是否在ToggleButtonInfo的dealloc中正确发布了它?

显示更多代码会有所帮助。

答案 1 :(得分:2)

通过您的代码,我会看到您调用alloc的几个地方。只要您拨打allocnewcopy,就必须致电releaseautorelease。我建议将NSMutableArray *persons = [[NSMutableArray alloc] init];更改为NSMutableArray *persons = [[[NSMutableArray alloc] init] autorelease];

保证自动释放的对象在方法调用期间可用。

此外,还有一个快速建议:如果您没有,请从Build and analyze菜单中查看Build

答案 2 :(得分:0)

我不知道如何解释你对 [info valueForKey:@“name”] @“其他东西”的发现,但看起来确实如此就像你在泄漏btn。在 [person addObject:btn]; 之后你应该 [btn release];

将btn添加到NSMutableArray人员将增加btn的保留计数(直到将其从人员中删除)。但是-alloc返回btn,保留计数为1,使您的方法成为其所有者。

答案 3 :(得分:0)

你的回程不应该是吗?

return [persons autorelease];