2013-08-07 77 views
1

我從服務器獲取數據並將它們轉換爲NSManagedObject對象數組。 該數組用於顯示錶格。如何在其他NSManagedObjectContext中插入NSManagedObject?

如何在持久性存儲中插入第一個元素數組

- (void)viewDidLoad 
{ 
    [self loadData]; 
    [self insertFirstPeople]; 
} 

- (NSManagedObjectContext *)managedObjectContext 
{ 
    if(!_managedObjectContext) _managedObjectContext = [NSManagedObjectContext MR_context]; 
    return _managedObjectContext; 
} 

- (void)loadData 
{ 
    ... 
     Network Request 
    ... 
    peoples = [NSMutableArray array]; 
    for (NSDictionary *item in items) 
    { 
     People *people = [Podcast MR_createInContext:self.managedObjectContext]; 
     people.name = [item valueForKeyPath:@"im:name.label"]; 
     [peoples addObject:people]; 
    } 
} 

-(void)insertFirstPeople 
{ 
    People *people = peoples[0]; 
    NSManagedObjectContext *moc = [NSManagedObjectContext MR_defaultContext]; 
    [moc insertObject:people] 
    [moc MR_saveToPersistentStoreAndWait]; 
} 

錯誤:

An NSManagedObject may only be in (or observed by) a single NSManagedObjectContext. 
+0

難道你打算使用兩個不同的管理對象上下文?你真的只想在默認上下文中插入* first * People對象嗎?在後臺環境中創建的其他對象呢? –

+0

是的。我想使用兩個上下文。第一個只創建一個表,第二個保存永久存儲 – user2168735

+0

確定,但是是否要將* all * People對象保存到持久存儲或僅保留第一個*對象? –

回答

0

我自己已經找到了解決問題的辦法。

-(void)insertFirstPeople 
{ 
    People *people = peoples[0]; 
    CoreDataHelper *helper = [[CoreDataHelper alloc] init]; 
    NSManagerObjectContext *context = [NSManagedObjectContext MR_defaultContext]; 
    [helper saveObject:people toContext:context]; 
    [context MR_saveOnlySelfAndWait]; 
} 

CoreDataHelper.h

#import <Foundation/Foundation.h> 


@interface CoreDataHelper : NSObject 
{ 
    NSMutableDictionary* _lookup; 
} 
@property(nonatomic, retain) NSMutableDictionary *lookup; 

-(void)saveFrom:(NSManagedObjectContext *)current to:(NSManagedObjectContext *)parent; 

- (NSManagedObject *)saveObject:(NSManagedObject *)object toContext:(NSManagedObjectContext *)moc; 

- (NSManagedObject*)copyObject:(NSManagedObject*)object 
        toContext:(NSManagedObjectContext*)moc 
         parent:(NSString*)parentEntity; 
@end 

CoreDataHelper.m

#import "CoreDataHelper.h" 

@implementation CoreDataHelper 

@synthesize lookup = _lookup; 

-(void)saveFrom:(NSManagedObjectContext *)current to:(NSManagedObjectContext *)parent 
{ 
    NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter]; 
      [dnc addObserverForName:NSManagedObjectContextDidSaveNotification 
          object:current queue:nil 
         usingBlock:^(NSNotification *notification) 
     { 
      [parent mergeChangesFromContextDidSaveNotification:notification]; 
     }]; 
     NSError *error; 
     if (![current save:&error]) 
      { 
       NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      } 

      [dnc removeObserver:self 
         name:NSManagedObjectContextDidSaveNotification 
         object:current]; 
} 


- (NSManagedObject *)saveObject:(NSManagedObject *)object toContext:(NSManagedObjectContext *)moc { 
    NSUndoManager *docUndoMgr = [moc undoManager]; 
    [docUndoMgr beginUndoGrouping]; 

    NSManagedObject *object2 = [self copyObject:object toContext:moc parent:nil]; 

    [moc processPendingChanges]; 
    [docUndoMgr endUndoGrouping]; 
    return object2; 
} 

- (NSManagedObject *)copyObject:(NSManagedObject *)object 
         toContext:(NSManagedObjectContext *)moc 
         parent:(NSString *)parentEntity; { 
    NSError *error = nil; 
    NSString *entityName = [[object entity] name]; 
    NSManagedObject *newObject = nil; 
    if ([moc objectRegisteredForID:object.objectID]) 
     newObject = [moc objectWithID:object.objectID]; 
    else 
     newObject = [NSEntityDescription 
       insertNewObjectForEntityForName:entityName 
         inManagedObjectContext:moc]; 


    if (![moc save:&error]) 
    { 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    } 

    [[self lookup] setObject:newObject forKey:[object objectID]]; 

    NSArray *attKeys = [[[object entity] attributesByName] allKeys]; 
    NSDictionary *attributes = [object dictionaryWithValuesForKeys:attKeys]; 

    [newObject setValuesForKeysWithDictionary:attributes]; 

    id oldDestObject = nil; 
    id temp = nil; 
    NSDictionary *relationships = [[object entity] relationshipsByName]; 
    for (NSString *key in [relationships allKeys]) { 

     NSRelationshipDescription *desc = [relationships valueForKey:key]; 
     NSString *destEntityName = [[desc destinationEntity] name]; 
     if ([destEntityName isEqualToString:parentEntity]) continue; 

     if ([desc isToMany]) { 

      NSMutableSet *newDestSet = [NSMutableSet set]; 

      for (oldDestObject in [object valueForKey:key]) { 
       temp = [[self lookup] objectForKey:[oldDestObject objectID]]; 
       if (!temp) { 
        temp = [self copyObject:oldDestObject 
            toContext:moc 
            parent:entityName]; 
       } 
       [newDestSet addObject:temp]; 
      } 

      [newObject setValue:newDestSet forKey:key]; 

     } else { 
      oldDestObject = [object valueForKey:key]; 
      if (!oldDestObject) continue; 

      temp = [[self lookup] objectForKey:[oldDestObject objectID]]; 
      if (!temp && ![destEntityName isEqualToString:parentEntity]) { 
       temp = [self copyObject:oldDestObject 
           toContext:moc 
           parent:entityName]; 
      } 

      [newObject setValue:temp forKey:key]; 
     } 
    } 

    return newObject; 
} 

@end 
相關問題