我自己也有同样的问题,发现这篇关于创建断开连接的实体的文章以后可以添加到上下文中:http: //locassa.com/temporary-storage-in-apples-coredata/
这个想法是你有一个 NSManagedObject 因为你将在数据库中存储对象。我的障碍是这些对象中有许多是通过 HTTP API 下载的,我想在会话结束时丢弃其中的大部分。想想一系列用户帖子,我只想保存那些被收藏或保存为草稿的帖子。
我使用创建所有帖子
+ (id)newPost {
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
Post *post = [[Post alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
return post;
}
然后当它们被收藏时,它们被插入到本地托管对象上下文中
+ (BOOL)favoritePost:(Post *)post isFavorite:(BOOL)isFavorite
{
// Set the post's isFavorite flag
post.isFavorite = [NSNumber numberWithBool:isFavorite];
// If the post is being favorited and not yet in the local database, add it
NSError *error;
if (isFavorite && [self.managedObjectContext existingObjectWithID:post.objectID error:&error] == nil) {
[self.managedObjectContext insertObject:post];
}
// Else if the post is being un-favorited and is in the local database, delete it
else if (!isFavorite && [self.managedObjectContext existingObjectWithID:post.objectID error:&error] != nil) {
[self.managedObjectContext deleteObject:post];
}
// If there was an error, output and return NO to indicate a failure
if (error) {
NSLog(@"error: %@", error);
return NO;
}
return YES;
}
希望有帮助。