2

I am getting data from the server and converts them to an array of NSManagedObject objects. The array is used to display the table.

How to insert first element array peoples in persistent store?

- (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];
}

Error:

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

1 回答 1

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
于 2013-08-08T10:29:01.767 回答