核心数据代码中的内存泄漏问题

时间:2011-07-08 20:07:41

标签: iphone objective-c memory-leaks

我似乎无法弄清楚Leaks工具报告问题的原因。有问题的代码在这里标有问题行。有任何想法吗?有没有办法确切地找出泄漏的对象是什么?

NSArray *getAllCoreData(NSString *entityName, NSString *orderedBy, BOOL ascending, BOOL shallow)
{
// Get the managed object context
NSManagedObjectContext *moc = [[AppController sharedAppController] managedObjectContext];

// Create a fetch request that fetches from 'entityName'
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc];
[fetch setEntity:entity];

// Try to do the fetch
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error]; <----- Problem line

[fetch release];

// Did the fetch fail?
if (!result)
{
    // Display an alert view
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Fetch Failed"
                                                        message:[error localizedDescription] 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];

    [alertView autorelease];
    [alertView show];
    return nil;
}

// Return the array of instances of NSManagedObject
return result;
}

任何帮助将不胜感激, 杰森

2 个答案:

答案 0 :(得分:1)

泄漏告诉你,在你没有更多的参考资料后,分配的内存一直存在。

因此,在您返回结果后,其他内容会保留太长时间,并且在您完成后不会释放。

答案 1 :(得分:1)

尝试更改

NSError *error;

NSError *error = nil;

这可能不是真正的泄漏。可能,NSError *error恰好在其中有一些剩余的指针,因此它看起来像是工具的泄漏。