“[CFString release]:使用CoreData时发送到解除分配实例的消息”

时间:2011-02-23 13:13:49

标签: iphone core-data memory-management ios4

我已经开始在我的项目中使用CoreData。没有CodeData的代码,我的项目工作得很好。我添加了从coreData项目模板访问NSManagedObjectContext的方法。现在我尝试使用以下代码创建新的CoreData对象:

- (void)saveSearchResultToHistory:(NSArray *) productsArray  {
   [productsArray retain];

   NSLog(@"context: %@", self.managedObjectContext);

   Product *product = [NSEntityDescription
                                   insertNewObjectForEntityForName:@"Product" 
                                   inManagedObjectContext:self.managedObjectContext];
product.productId = [(Product *) [productsArray objectAtIndex:0] productId];

NSError *error;
if (![self.managedObjectContext save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}


[productsArray release];
}

当这个方法运行一次然后一切都很好,当我尝试第二次运行它时,处理停止在:

Product *product = [NSEntityDescription
                                   insertNewObjectForEntityForName:@"Product" 
                                   inManagedObjectContext:self.managedObjectContext];

在控制台中显示以下错误消息:

  

[CFString retain]:消息发送到解除分配的实例0x5a23b0

任何想法可能出错? 谢谢!

1 个答案:

答案 0 :(得分:0)

首先,每次添加内容时都不需要保存上下文,只需在应用关闭或进入后台时保存。

你得到的错误看起来像你在某处释放NSString。

要检查错误是否在coredata上下文中,请使用此保存功能:

- (void)saveContext {
    if ([self.managedObjectContext hasChanges]) {
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {

            dbgPrint(@"Failed to save to data store: %@", [error localizedDescription]);

            NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];

            if (detailedErrors != nil && [detailedErrors count] > 0) {
                for(NSError* detailedError in detailedErrors) {
                    dbgPrint(@"--DetailedError: %@", [detailedError userInfo]);
                }
            } else {
                dbgPrint(@"  %@", [error userInfo]);
            }
        }
    }   
}