2011-02-23 93 views
0

我已经开始在我的项目中使用CoreData。没有CodeData的代码,我的项目工作得很好。我添加了从coreData项目模板访问NSManagedObjectContext的方法。现在,我尝试创建新CoreData对象用下面的代码:“[CFString发布]:消息发送到释放实例”使用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字符串挽留]:消息发送到释放的实例0x5a23b0

任何想法可能是错误的? 谢谢!

回答

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]); 
      } 
     } 
    } 
}  
+0

是,节能的背景下只有一次,在某处年底才有意义。感谢您指出了这一点! – Jakub 2011-02-23 14:23:58

相关问题