开发者

When I solve this potential leak with autorelease my app crashes, why?

the analyze function tells me that there is a potential leak at mutableFetchResults here:

- (NSMutableArray *) getBookmarks
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bookmark" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
[request release];


if (!mutableFetchResults) {
    NSLog(@"Error with fetch: %@", error );
    return nil;
}
开发者_如何学Python
return mutableFetchResults ;

}

Like this it works, but with a leak warning.

When I use autorelease NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; my app crashes without an error log.

How can I find out the problem here?

- (id)init
{
self = [super init];
if (self) {

    coreDataManager = [[CoreDataManager alloc] initWithDelegate:self];
    bookmarks = [coreDataManager getBookmarks];
  }
return self;
}


You need to retain anything you want to keep around, so your init method needs to retain the bookmarks:

bookmarks = [[coreDataManager getBookmarks] retain];

Then you can autorelease the mutableFetchResults variable before returning it.

Also, the Cocoa naming convention would have the getBookmarks method named bookmarks. :)


What do you mean when you say:

When I use autorelease NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; my app crashes without an error log.

...there's no autorelease there. mutableCopy retains a copy of your array with a retain count of 1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜