CoreData与获取的结果数组一起泄漏

时间:2011-06-20 18:02:41

标签: arrays ios core-data memory-leaks

我正在使用CoreData来存储汽车,旅行,从GPS记录的数据等对象。 当我拿到我要显示的旅行列表,旅行的一些统计数据,或者在我的设置视图控制器中添加新车时,我几乎使用了这种请求:

- (void)getDataTrip
{
    // Fetched data trips.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DataTrip" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set predicate and sort orderings...
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    [sortDescriptors release];
    [sortDescriptor release];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idTrip = %@", self.idTrip];
    [fetchRequest setPredicate:predicate];

    // Execute the fetch -- create a mutable copy of the result.
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
        NSLog(@"failed with error: %@", error);
    }

    // Set the array.
    [self setDataTripArray:mutableFetchResults];

    // Memory management.
    [fetchRequest release];
    [mutableFetchResults release];
}

有时,当我[self setDataTripArray:mutableFetchResults];时,我有泄漏,有时没有。在这种情况下,当我获取行程数据时,当我使用导航控制器返回到根视图控制器(显示行程列表)和/或当我更改标签时,它会一直泄漏。

无论如何,它只是泄漏而且它总是来自从CoreData获取数据,并将此数组提供给我的本地数组var。

如果你看到如何解决这个问题,请告诉我!一段时间后,它让应用程序崩溃了。 谢谢!

1 个答案:

答案 0 :(得分:1)

<强>解

我在创建另一个用于为滚动视图创建图形的UIViewController时,发现我在对象retain对象上执行了dataTripArray

- (void)loadScrollViewWithPage:(int)page
{
    if (page < 0)
        return;
    if (page >= kNumberOfPages)
        return;

    // Replace the placeholder if necessary.
    GraphController *controller = [self.graphControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null])
    {
        controller = [[GraphController alloc] initWithPageNumber:page data:[self.dataTripArray retain]];
        [self.graphControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
    }

    // Add the controller's view to the scroll view.
    if (controller.view.superview == nil)
    {
        CGRect frame = _scrollView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
        controller.view.frame = frame;
        [self.scrollView addSubview:controller.view];
    }
}

我刚删除retain,泄漏不再出现。固定!