开发者

Application seems to be leaking memory

In a garbage collected environment, I am building an application that is using Core Data and Sync Services. The core data model and store is a representation of the Address Book Contact information (as described by Apple here).

The goal of the application is to synchronize the contacts in the address book via sync services, with our online service. This means parsing changes (adds, updates, deletes) within the Core Data store, which will later be picked up by Sync Services (and viceversa).

However, it seems that when I create Core Data objects, they never get deallocated.The code I'm using is as follows (I have narrowed the leak down to the following instruction):


    SLSyncLog *syncLog = [SLSyn开发者_如何学GocLog singletonFromContext:context];


+ (SLSyncLog *)singletonFromContext:(NSManagedObjectContext *)context {
    NSEntityDescription *syncDataDescription = [SLSyncLog entityInManagedObjectContext:context];
    return (SLSyncLog *)[SLSingletonLoader loadSingletonOfEntity:syncDataDescription fromContext:context];
}


+ (NSManagedObject *)loadSingletonOfEntity:(NSEntityDescription *)entity fromContext:(NSManagedObjectContext *)context {
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];

    NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    [request release];

    if (error) {
        [NSException raise:kSyncDataException format:@"Error retrieving %@ object", [entity name]];
    }

    if ([results count] > 1) {
        [NSException raise:kSyncDataException
                    format: @"There were %d %@ objects, instead of the expected one.", [entity name], [results count]];
    }

    NSManagedObject *log = nil;
    if ([results count] == 0) {
        /* Create the singleton object. */
        log = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
                                            inManagedObjectContext:context];
    } else {
        log = [results objectAtIndex:0];
    }

    return log;
}

As far as I see it, this being in a garbage collected environment, it should clean up whatever is created in these methods. Is it a Core Data specific problem?

Any help will be appreciated. Thanks!


In theory, you should be given back the same array of objects each time because Core Data caches them behind the scenes. Just because you think they are no longer being referenced anywhere, doesn't mean they aren't. And they definitely aren't going to go away until you have saved the managed object context.

By the way, the correct pattern for error handling is to test the return value for nil and only then check the NSError.


No.

CoreData will hold on to a reference to the managed objects created inside that method until the instance of NSManagedObjectContext with which they are associated is released or reset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜