我在 nil 托管对象上下文中创建 NSManagedObject 的实例,因为我不希望保存对象,除非用户稍后选择。
我通过使用上下文创建实体描述然后在没有上下文的情况下创建对象本身来做到这一点。这如下所示。
NZVideo *video = nil;
if ([[tempVideo objectForKey:_kResponseVideoTypeKey] isEqualToString:_kVideoTypeYouTube] == YES)
{
NSEntityDescription *entityDescription = [NZYouTubeVideo entityDescriptionInContext:[NSManagedObjectContext contextForCurrentThread]];
video = (NZVideo *)[[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
[(NZYouTubeVideo *)video setVideoId:[media objectForKey:_kResponseVideoIdKey]];
}
else if ([[tempVideo objectForKey:_kResponseVideoTypeKey] isEqualToString:_kVideoTypeS3] == YES)
{
NSEntityDescription *entityDescription = [NZS3Video entityDescriptionInContext:[NSManagedObjectContext contextForCurrentThread]];
video = (NZVideo *)[[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
[(NZS3Video *)video setAbsoluteVideoUrl:[media objectForKey:_kResponseVideoUrlKey]];
}
[video setTitle:title];
[video setSummary:summary];
[video setDurationValue:duration];
if (tempThumbnails != nil)
{
NSString *smallThumbnail = [tempThumbnails objectForKey:_kResponseVideoThumbnailSmallKey];
if (smallThumbnail != nil)
{
NSEntityDescription *entityDescription = [NZThumbnail entityDescriptionInContext:[NSManagedObjectContext contextForCurrentThread]];
NZThumbnail *thumbnail = (NZThumbnail *)[[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
[thumbnail setAbsoluteImageUrl:smallThumbnail];
[thumbnail setAbsoluteSizeValue:NZThumbnailSizeSmall];
[video addThumbnailsObject:thumbnail];
}
}
if (video != nil)
{
[videos addObject:video];
}
然后,当我想保存对象时,我将它们添加到托管对象上下文中。我还添加了该对象与之有关系的所有对象。
[MagicalRecord saveUsingCurrentThreadContextWithBlock:^(NSManagedObjectContext *context) {
id _video = nil;
if ([video isKindOfClass:[NZYouTubeVideo class]])
{
_video = (NZYouTubeVideo *)video;
}
else if ([video isKindOfClass:[NZS3Video class]])
{
_video = (NZS3Video *)video;
}
if (((NSManagedObject *)_video).managedObjectContext == nil)
{
[context insertObject:_video];
}
for (NZThumbnail *thumbnail in ((NZVideo *)_video).thumbnails)
{
[context insertObject:thumbnail];
}
[playlist addVideosObject:video];
}
completion:^(BOOL success, NSError *error) {
if (error != nil)
{
DDLogVerbose(@"%@", error);
}
}];
但是,当重新启动应用程序时,对象已添加到 Core Data,但对象上的所有属性都是null
.
有谁知道为什么会发生这种情况以及如何让它存储属性?如前所述,对象存在。它们是持久的,但所有属性都是空的。
我认为这没有什么区别,但我使用MagicalRecord来创建、保存和检索实体。