I'm having trouble dealing with object IDs in CoreData. I'm using MagicalRecord for convenience and have 3 contexts: a private queue working context, a main queue context for UI and parent to the working context, and a private queue saving context that is the parent of the main context.
My goal is to create an object in the working context, save to the persistent store, save it's objectID URL to NSUserDefaults, and then be able to pull out that MO using the objectID later on. However, what I'm finding is that after saving the permanent ID of the object is changing.
In the console output below you can see that after I request the permanent ID the value I get back is "F474F6EE-A225-456B-92EF-AB1407336F15/CDBaseAccount/p1" but later when I list all the objects in CD the only object there has the ID "F474F6EE-A225-456B-92EF-AB1407336F15/CDBaseAccount/p2". p1 vs p2, what happened?
Code:
NSManagedObjectContext *c = [NSManagedObjectContext MR_contextThatPushesChangesToDefaultContext];
[c performBlockAndWait:^{
NSArray *all = [CDBaseAccount MR_findAllInContext:c];
NSLog(#"count: %d", all.count);
NSLog(#"all accounts = %#", all);
CDBaseAccount *a = [CDBaseAccount MR_createInContext:c];
a.accountName = #"foo";
[c MR_saveNestedContexts];
NSLog(#"temp a.objectID = %#", a.objectID);
NSError *error;
if (![c obtainPermanentIDsForObjects:#[a] error:&error]) {
NSLog(#"perm id error: %#", error);
return;
}
NSLog(#"perm a.objectID = %#", a.objectID);
NSURL *u = a.objectID.URIRepresentation;
dispatch_async(dispatch_get_main_queue(), ^{
NSManagedObjectContext *d = [NSManagedObjectContext MR_defaultContext];
NSArray *all = [CDBaseAccount MR_findAllInContext:d];
NSLog(#"count: %d", all.count);
NSLog(#"all accounts = %#", all);
NSManagedObjectID *i = [d.persistentStoreCoordinator managedObjectIDForURIRepresentation:u];
NSError *objWithIdError = nil;
NSManagedObject *o = [d existingObjectWithID:i error:&objWithIdError];
if (objWithIdError != nil) {
NSLog(#"existing object error: %#", objWithIdError);
return;
}
NSLog(#"o = %#", o);
NSLog(#"o.objectID = %#", o.objectID);
});
}];
Console output:
> +[NSManagedObjectContext(MagicalRecord) MR_contextWithStoreCoordinator:](0xa7c9b0) -> Created <NSManagedObjectContext: 0x83522a0>: Context *** MAIN THREAD ***
> count: 0
> all accounts = (
> )
> -[NSManagedObjectContext(MagicalSaves) MR_saveWithErrorCallback:](0x8353de0) -> Saving <NSManagedObjectContext: 0x8353de0>: Context *** MAIN THREAD ***
> -[NSManagedObjectContext(MagicalSaves) MR_saveWithErrorCallback:](0x8195450) -> Saving <NSManagedObjectContext: 0x8195450>: *** DEFAULT *** Context *** MAIN THREAD ***
> -[NSManagedObjectContext(MagicalSaves) MR_saveWithErrorCallback:](0x83522a0) -> Saving <NSManagedObjectContext: 0x83522a0>: *** BACKGROUND SAVE *** Context *** MAIN THREAD ***
> temp a.objectID = 0x8187ee0 <x-coredata:///CDBaseAccount/tF392AC6A-3539-4F39-AC53-35F9E5B3C9322>
> perm a.objectID = 0x8355800 <x-coredata://F474F6EE-A225-456B-92EF-AB1407336F15/CDBaseAccount/p2>
> count: 1
> all accounts = (
"<CDBaseAccount: 0x844ca60> (entity: CDBaseAccount; id: 0x844a4c0 <x-coredata://F474F6EE-A225-456B-92EF-AB1407336F15/CDBaseAccount/p1> ; data: <fault>)"
)
> existing object error: Error Domain=NSCocoaErrorDomain Code=133000 "The operation couldn’t be completed. (Cocoa error 133000.)" UserInfo=0x864d8c0 {NSAffectedObjectsErrorKey=(
"<CDBaseAccount: 0x864b8c0> (entity: CDBaseAccount; id: 0x86405c0 <x-coredata://F474F6EE-A225-456B-92EF-AB1407336F15/CDBaseAccount/p2> ; data: <fault>)"
)}
Short answer is, don't do that :)
-objectID is not reliable between launches of your application. It is guaranteed to be unique and reliable under the following conditions:
Within a single lifecycle of the application
In its original object form (not in URL or NSString form)
Treating the -objectID as a permanent unique identifier to be stored outside of the persistent store is going to fail you fairly often. Core Data changes the underlying details of the -objectID many times during the life of the object.
If you need an externally reliable unique then you need to create one yourself. I generally recommend adding a [[NSProcessInfo processInfo] globallyUniqueString] to any entity that needs an externally reference-able unique. -awakeFromInsert is a great place to do that.
This may be because you're using nested context.
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
static NSArray *fetchAllPersons(NSManagedObjectContext *moc);
static NSManagedObjectModel *managedObjectModel();
static NSManagedObjectContext *createManagedObjectContext();
static NSURL *desktopDirectoryURL(void);
static void testObjectID(void);
int main(int argc, const char * argv[])
{
#autoreleasepool {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
testObjectID();
});
}
dispatch_main();
return 0;
}
static void testObjectID(void)
{
NSManagedObjectContext *c = createManagedObjectContext();
[c performBlock:^{
NSArray *all = fetchAllPersons(c);
NSLog(#"count: %lu", all.count);
NSLog(#"all accounts = %#", all);
NSManagedObject *a = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:c];
[a setValue:#"foo" forKey:#"name"];
NSLog(#"temp a.objectID = %#", a.objectID);
NSError *error = nil;
NSCAssert([c obtainPermanentIDsForObjects:#[a] error:&error], #"perm id error: %#", error);
NSLog(#"perm a.objectID = %#", a.objectID);
NSCAssert([c save:&error], #"Save failed: %#", error);
NSURL *u = a.objectID.URIRepresentation;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSManagedObjectContext *d = createManagedObjectContext();
NSArray *all = fetchAllPersons(c);
NSLog(#"count: %lu", all.count);
NSLog(#"all accounts = %#", all);
NSManagedObjectID *i = [d.persistentStoreCoordinator managedObjectIDForURIRepresentation:u];
NSError *objWithIdError = nil;
NSManagedObject *o = [d existingObjectWithID:i error:&objWithIdError];
NSCAssert(o != nil, #"existing object error: %#", objWithIdError);
NSLog(#"o = %#", o);
NSLog(#"o.objectID = %#", o.objectID);
});
}];
}
static NSArray *fetchAllPersons(NSManagedObjectContext *moc)
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Person"];
NSError *error = nil;
NSArray *result = [moc executeFetchRequest:request error:&error];
NSCAssert(result != nil, #"Fetch failed: %#", error);
return result;
}
static NSManagedObjectModel *managedObjectModel()
{
static NSManagedObjectModel *mom = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSEntityDescription *personEntity = [[NSEntityDescription alloc] init];
[personEntity setName:#"Person"];
NSAttributeDescription *nameAttribute = [[NSAttributeDescription alloc] init];
[nameAttribute setName:#"name"];
[nameAttribute setAttributeType:NSStringAttributeType];
[personEntity setProperties:#[nameAttribute]];
mom = [[NSManagedObjectModel alloc] init];
[mom setEntities:#[personEntity]];
});
return mom;
}
static NSManagedObjectContext *createManagedObjectContext()
{
static NSPersistentStoreCoordinator *coordinator;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel()];
NSString *STORE_TYPE = NSSQLiteStoreType;
NSString *STORE_FILENAME = #"foobar.db";
NSError *error;
NSURL *url = [desktopDirectoryURL() URLByAppendingPathComponent:STORE_FILENAME];
NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE
configuration:nil URL:url options:nil
error:&error];
if (newStore == nil) {
NSLog(#"Store Configuration Failure\n%#",
([error localizedDescription] != nil) ?
[error localizedDescription] : #"Unknown Error");
}
});
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[moc setPersistentStoreCoordinator:coordinator];
return moc;
}
static NSURL *desktopDirectoryURL(void)
{
static NSURL *URL;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
URL = [fileManager URLForDirectory:NSDesktopDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
NSCAssert(URL != nil, #"Could not access Desktop directory: %#", [error localizedDescription]);
});
return URL;
}
Outputs:
count: 0
all accounts = (
)
temp a.objectID = 0x10180e640 <x-coredata:///Person/tB1D48677-0152-4DA9-8573-7C7532863B4E2>
perm a.objectID = 0x101901bb0 <x-coredata://275C90E5-2598-4DFA-BF4C-E60A336E8BE4/Person/p1>
count: 1
all accounts = (
"<NSManagedObject: 0x10180e5b0> (entity: Person; id: 0x101901bb0 <x-coredata://275C90E5-2598-4DFA-BF4C-E60A336E8BE4/Person/p1> ; data: {\n name = foo;\n})"
)
o = <NSManagedObject: 0x100416530> (entity: Person; id: 0x100415b60 <x-coredata://275C90E5-2598-4DFA-BF4C-E60A336E8BE4/Person/p1> ; data: {
name = foo;
})
o.objectID = 0x100415b60 <x-coredata://275C90E5-2598-4DFA-BF4C-E60A336E8BE4/Person/p1>
Related
I setup a background thread with the Parent/Child model. Essentially the context save is failing.
Here is my setup. In the AppDelegate i've setup the _managedObjectContext with the NSMainQueueConcurrencyType:
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];//[[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
In my data loading class I setup the parent/child mocs here to perform the work on the background thread:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSManagedObjectContext *mainMOC = self.managedObjectContext;
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
[moc setParentContext:mainMOC];
[moc setUndoManager:nil];
When the json data has completed I attempt to peform a save operation with the following macro:
#define SAVE_MOC { NSError *error; \
if (![moc save:&error]) { NSLog(#"Sub MOC Error"); } \
[mainMOC performBlock:^{ NSError *e = nil; if (![mainMOC save:&e]) {
NSLog(#"Main MOC Error %#",error.localizedDescription);}}];}
Also when i've completed the data load I jump back on the main thread like this:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"<---- complete CS sub moc! ---->");
//this fires ok
});
So, from my SAVE_MOC macro i just get a simple error:
Main MOC Error (null)
Let me know if I can provide more info. I'm very new to multi-threading and trying to get a better handle on this approach.
Thanks,
Josh
In my data loading class I setup the parent/child mocs here to perform
the work on the background thread:
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSManagedObjectContext *mainMOC = self.managedObjectContext;
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
You should not do that. Do this instead.
NSManagedObjectContext *mainMOC = self.managedObjectContext;
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
Make sure you access the MOC in a performBlock. For example,
[moc performBlock:^{
// Anything at all involving this MOC or any of its objects
}];
When the json data has completed I attempt to peform a save operation
with the following macro:
Consider saving with something like this. Your completion block will be called when the save has finished.
- (void)saveMOC:(NSManagedObjectContext*)moc
completion:(void(^)(NSError *error))completion {
[moc performBlock:^{
NSError *error = nil;
if ([moc save:&error]) {
if (moc.parentContext) {
return [self saveMOC:moc.parentContext completion:completion];
}
}
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(error);
});
}
}];
}
[self saveMOC:moc completion:^(NSError *error) {
// Completion handler is called from main-thread, after save has finished
if (error) {
// Handle error
} else {
}
}];
EDIT
This code will crash if moc.parentContext is main concurrency type. –
Mundi
There is no inherent reason that the code I posted should cause a crash with a parent MOC of NSMainQueueConcurrencyType. It has supported being a parent context ever since parent/child was added to Core Data.
Maybe I was missing a typo, so I copy/paste saveMOC:completion: straight from this answer, and wrote the following test helper.
- (void)testWithChildConcurrencyType:(NSManagedObjectContextConcurrencyType)childConcurrencyType
parentConcurrencyType:(NSManagedObjectContextConcurrencyType)parentConcurrencyType {
NSAttributeDescription *attr = [[NSAttributeDescription alloc] init];
attr.name = #"attribute";
attr.attributeType = NSStringAttributeType;
NSEntityDescription *entity = [[NSEntityDescription alloc] init];
entity.name = #"Entity";
entity.properties = #[attr];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] init];
model.entities = #[entity];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
[psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL];
NSManagedObjectContext *parent = [[NSManagedObjectContext alloc] initWithConcurrencyType:parentConcurrencyType];
parent.persistentStoreCoordinator = psc;
NSManagedObjectContext *child = [[NSManagedObjectContext alloc] initWithConcurrencyType:childConcurrencyType];
child.parentContext = parent;
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Entity" inManagedObjectContext:child];
[obj setValue:#"value" forKey:#"attribute"];
XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:#"save from %# to %# finished", concurrencyTypeString(childConcurrencyType), concurrencyTypeString(parentConcurrencyType)]];
[self saveMOC:child completion:^(NSError *error) {
// Verify data saved all the way to the PSC
NSManagedObjectContext *localMoc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
localMoc.persistentStoreCoordinator = psc;
NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:#"Entity"];
XCTAssertEqualObjects(#"value", [[[localMoc executeFetchRequest:fr error:NULL] firstObject] valueForKey:#"attribute"]);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:10 handler:nil];
}
And then, I wrote a test for each possible parent/child relationship.
- (void)testThatDoingRecursiveSaveFromPrivateToPrivateWorks {
[self testWithChildConcurrencyType:NSPrivateQueueConcurrencyType
parentConcurrencyType:NSPrivateQueueConcurrencyType];
}
- (void)testThatDoingRecursiveSaveFromPrivateToMainWorks {
[self testWithChildConcurrencyType:NSPrivateQueueConcurrencyType
parentConcurrencyType:NSMainQueueConcurrencyType];
}
- (void)testThatDoingRecursiveSaveFromMainToPrivateWorks {
[self testWithChildConcurrencyType:NSMainQueueConcurrencyType
parentConcurrencyType:NSPrivateQueueConcurrencyType];
}
- (void)testThatDoingRecursiveSaveFromMainToMainWorks {
[self testWithChildConcurrencyType:NSMainQueueConcurrencyType
parentConcurrencyType:NSMainQueueConcurrencyType];
}
So, what am I missing?
As I write this, I am reminded of a 360iDev presentation where the presenter said that you can't call performBlock on a NSMainQueueConcurrencyType context. At the time, I thought he just misspoke, meaning confinement, but maybe there is some confusion in the community about this.
You can't call performBlock on a NSConfinementConcurrencyType MOC, but performBlock is fully supported for NSMainQueueConcurrencyType.
I'm using RestKit and RRNCollapsableTable. The problem is, when I load view for the first time, RestKit is downloading data from JSON. That delay causes menu to not load. What I'm trying to do is to make CollapsableTable wait for data.
[self requestData:^(BOOL success) {
if (success) {
_menu = [self buildMenu];
[self model];
}
}];
- (void)requestData:(void (^)(BOOL success))completionBlock {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Messages"];
NSSortDescriptor *byId = [NSSortDescriptor sortDescriptorWithKey:#"customNewsId" ascending:YES];
fetchRequest.sortDescriptors = #[byId];
NSError *error = nil;
// Setup fetched results
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext
sectionNameKeyPath:#"customNewsId"
cacheName:nil];
//[self.fetchedResultsController setDelegate:self];
BOOL fetchSuccessful = [self.fetchedResultsController performFetch:&error];
if (!fetchSuccessful) {
abort();
}
[[RKObjectManager sharedManager] getObjectsAtPath:#"api/json/get/bZmroLaBCG" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"Load complete: Table should refresh...");
//[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"LastUpdatedAt"];
//[[NSUserDefaults standardUserDefaults] synchronize];
NSError *error = nil;
if ([[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext hasChanges] && ![[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext saveToPersistentStore:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
completionBlock(YES);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Load failed with error: %#", error);
completionBlock(NO);
}];
completionBlock(YES);
}
Then BuildMenu is just iterating over fetched objects and put them in section.
-(NSArray *)buildMenu {
__block NSMutableArray *collector = [NSMutableArray new];
NSInteger sections = [self.fetchedResultsController.sections count];
for (NSInteger i = 0; i < sections; i++) {
Messages *message = [_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
MenuSection *section = [MenuSection new];
section.items = #[message.message,message.pushNotificationMessage];
section.title = message.title;
NSLog(#"section.title - %#",section.title);
[collector addObject:section];
}
return [collector copy];
}
Method model is responsible for DataSource for CollapsableTable.
-(NSArray *)model {
return _menu;
}
Thanks in advance for any help.
Greetings.
I have a Core Data data model such as
I want to display the Teams.name associated with each Batting object in my UITableViewCell. When I try to access batting.teams.name it returns NULL.
My opening view controller has a string passed in then creates a new viewController with NSPredicate based from Master.nameLast and lists all names matching
and the NSFetchedResultsController which created the above list
#pragma mark - Fetched Results Controller Section
- (NSFetchedResultsController *)fetchedResultsController {
if(_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Master" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"debut" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"nameLast = [c]%#", lastName];
[fetchRequest setPredicate:predicate];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
return _fetchedResultsController;
}
My next view controller then lists all Batting properties associated with the selected Master NSManagedObject.
But when I try to access batting.teams.name it returns NULL!!!!! If I NSLog the entity from my delegate they are set but I can't access Teams.name from it's Batting.teams relationship
#pragma mark - Fetched Results Controller Section
- (NSFetchedResultsController *)fetchedResultsController {
if(_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Batting" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"yearID" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"playerID = %# " , selectedMaster.playerID];
[fetchRequest setPredicate:predicate];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
return _fetchedResultsController;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"playerStats" forIndexPath:indexPath];
Batting *batting = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *team = batting.teams.name; //NULL NULL NULL
// Configure the cell...
double average = [batting.h doubleValue]/[batting.ab doubleValue];
NSString *averageStr = [[NSString stringWithFormat:#"%.3f", average] substringFromIndex:1];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", batting.yearID, batting.teams.name];
cell.detailTextLabel.text = [NSString stringWithFormat:#"H: %#, AVG: %#, HR: %#, RBI: %#, SB: %#, R: %#, BB: %#, K: %#",
batting.h, averageStr , batting.hr, batting.rbi, batting.sb, batting.r, batting.bb, batting.so];
cell.detailTextLabel.textColor = [UIColor grayColor];
return cell;
}
returns null for the second argument????????
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", batting.yearID, batting.teams.name];
and this is the Teams entity logged from the AppDelegate
//
// AppDelegate.m
// Baseball Stats
//
// Created by Jason Steindorf on 6/6/15.
// Copyright (c) 2015 Jason Steindorf. All rights reserved.
//
#import "AppDelegate.h"
#import "Master.h"
#import "Teams.h"
#import "Batting.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSError *error;
NSString* dataPath_MASTER = [[NSBundle mainBundle] pathForResource:#"master" ofType:#"json"];
NSArray* MASTER = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_MASTER]
options:kNilOptions
error:&error];
NSString* dataPath_TEAMS = [[NSBundle mainBundle] pathForResource:#"teams" ofType:#"json"];
NSArray* TEAMS = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_TEAMS]
options:kNilOptions
error:&error];
NSString* dataPath_ABC = [[NSBundle mainBundle] pathForResource:#"abc" ofType:#"json"];
NSArray* BATTING_ABC = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_ABC]
options:kNilOptions
error:&error];
NSString* dataPath_DEFGH = [[NSBundle mainBundle] pathForResource:#"defgh" ofType:#"json"];
NSArray* BATTING_DEFGH = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_DEFGH]
options:kNilOptions
error:&error];
NSString* dataPath_IJKLM = [[NSBundle mainBundle] pathForResource:#"ijklm" ofType:#"json"];
NSArray* BATTING_IJKLM = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_IJKLM]
options:kNilOptions
error:&error];
NSString* dataPath_NOPQR = [[NSBundle mainBundle] pathForResource:#"nopqr" ofType:#"json"];
NSArray* BATTING_NOPQR = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_NOPQR]
options:kNilOptions
error:&error];
NSString* dataPath_ST = [[NSBundle mainBundle] pathForResource:#"st" ofType:#"json"];
NSArray* BATTING_ST = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_ST]
options:kNilOptions
error:&error];
NSString* dataPath_UVWXYZ = [[NSBundle mainBundle] pathForResource:#"uvwxyz" ofType:#"json"];
NSArray* BATTING_UVWXYZ = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_UVWXYZ]
options:kNilOptions
error:&error];
// Test listing all Master from the store
NSFetchRequest *fetchRequestMaster = [[NSFetchRequest alloc] init];
NSEntityDescription *entityMaster = [NSEntityDescription entityForName:#"Master" inManagedObjectContext:self.managedObjectContext];
[fetchRequestMaster setEntity:entityMaster];
NSArray *fetchedObjectsMaster = [self.managedObjectContext executeFetchRequest:fetchRequestMaster error:&error];
NSLog(#"Number of records in master.json - %d", (int)[fetchedObjectsMaster count]);
for (id m in MASTER) {
Master *master = [NSEntityDescription insertNewObjectForEntityForName:#"Master"
inManagedObjectContext:self.managedObjectContext];
master.nameFirst = [m objectForKey:#"nameFirst"];
master.nameLast = [m objectForKey:#"nameLast"];
master.debut = [m objectForKey:#"debut"];
master.playerID = [m objectForKey:#"playerID"];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
fetchedObjectsMaster = [self.managedObjectContext executeFetchRequest:fetchRequestMaster error:&error];
for (Master *master in fetchedObjectsMaster) {
NSLog(#"first name: %#", master.nameFirst);
NSLog(#"last name: %#", master.nameLast);
NSLog(#"debut: %#", master.debut);
NSLog(#"playerID: %#\n\n", master.playerID);
}
// Test listing all Master from the store
NSFetchRequest *fetchRequestTeams = [[NSFetchRequest alloc] init];
NSEntityDescription *entityTeams = [NSEntityDescription entityForName:#"Teams" inManagedObjectContext:self.managedObjectContext];
[fetchRequestTeams setEntity:entityTeams];
NSArray *fetchedObjectsTeams = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
NSLog(#"Number of records in teams.json - %d", (int)[fetchedObjectsTeams count]);
for (id t in TEAMS) {
Teams *team = [NSEntityDescription insertNewObjectForEntityForName:#"Teams"
inManagedObjectContext:self.managedObjectContext];
team.name = [t objectForKey:#"name"];
team.minYearID = [t objectForKey:#"minYearID"];
team.maxYearID = [t objectForKey:#"maxYearID"];
team.teamID = [t objectForKey:#"teamID"];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
fetchedObjectsTeams = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
for (Teams *team in fetchedObjectsTeams) {
NSLog(#"name: %#", team.name);
NSLog(#"minYearID: %#", team.minYearID);
NSLog(#"maxYearID: %#", team.maxYearID);
NSLog(#"teamID: %#\n\n", team.teamID);
}
NSFetchRequest *fetchRequestBatting = [[NSFetchRequest alloc] init];
NSEntityDescription *entityBatting = [NSEntityDescription entityForName:#"Batting" inManagedObjectContext:self.managedObjectContext];
[fetchRequestBatting setEntity:entityBatting];
NSArray *fetchedObjectsBatting = [self.managedObjectContext executeFetchRequest:fetchRequestBatting error:&error];
NSLog(#"Number of records in battingFiles.json - %d", (int)[fetchedObjectsBatting count]);
for (id b in BATTING_UVWXYZ) {
Batting *batting = [NSEntityDescription insertNewObjectForEntityForName:#"Batting"
inManagedObjectContext:self.managedObjectContext];
batting.playerID = [b objectForKey:#"playerID"];
batting.h = [b objectForKey:#"h"];
batting.ab = [b objectForKey:#"ab"];
batting.hr = [b objectForKey:#"hr"];
batting.rbi = [b objectForKey:#"rbi"];
batting.sb = [b objectForKey:#"sb"];
batting.r = [b objectForKey:#"r"];
batting.bb = [b objectForKey:#"bb"];
batting.so = [b objectForKey:#"so"];
batting.yearID = [b objectForKey:#"yearID"];
batting.teamID = [b objectForKey:#"teamID"];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
fetchedObjectsBatting = [self.managedObjectContext executeFetchRequest:fetchRequestBatting error:&error];
for (Batting *b in fetchedObjectsBatting) {
NSLog(#"playerID: %#", b.playerID);
NSLog(#"h: %#", b.h);
NSLog(#"ab: %#", b.ab);
NSLog(#"hr: %#", b.hr);
NSLog(#"rbi: %#", b.rbi);
NSLog(#"sb: %#", b.sb);
NSLog(#"r: %#", b.r);
NSLog(#"bb: %#", b.bb);
NSLog(#"so: %#", b.so);
NSLog(#"yearID: %#", b.yearID);
NSLog(#"teamID: %#\n\n", b.teamID);
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "steindorf.Baseball_Stats" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Baseball_Stats" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Baseball_Stats.sqlite"];
NSLog(#"%#", storeURL);
NSError *error = nil;
NSString *failureReason = #"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = #"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:#"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#end
In the block below, you need to assign the team to batting.
batting.teams = {your_team_object}
Then you will be able to access the team information. You can create another fetch to Core Data using the teamID to retrieve the team object.
for (id b in BATTING_UVWXYZ) {
Batting *batting = [NSEntityDescription insertNewObjectForEntityForName:#"Batting"
inManagedObjectContext:self.managedObjectContext];
batting.playerID = [b objectForKey:#"playerID"];
batting.h = [b objectForKey:#"h"];
batting.ab = [b objectForKey:#"ab"];
batting.hr = [b objectForKey:#"hr"];
batting.rbi = [b objectForKey:#"rbi"];
batting.sb = [b objectForKey:#"sb"];
batting.r = [b objectForKey:#"r"];
batting.bb = [b objectForKey:#"bb"];
batting.so = [b objectForKey:#"so"];
batting.yearID = [b objectForKey:#"yearID"];
batting.teamID = [b objectForKey:#"teamID"];
NSPredicate *teamIDPredicate = [NSPredicate predicateWithFormat:#"teamID == %#", [b objectForKey:#"teamID"]];
[fetchRequestTeams setPredicate:predicate];
NSArray *fetchedSpecificTeam = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
batting.teams= [fetchedSpecificTeam objectAtIndex:0];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
I have a routine that fetches RSS entries in the background and insert these in my NSManagedObjectContext if not already there.
My problem is that this object doesn't find duplicates or crashes, depending on which NSManagedObjectContext I use... Help me, please.
Here's the simplified .h
#interface AsyncFetchEngine : NSObject <NSXMLParserDelegate,NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) dispatch_queue_t rssParserQueue;
#property (strong, nonatomic) NSMutableArray *uRLsToFetch;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (strong, nonatomic) NSManagedObjectContext *childManagedObjectContext;
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
- (Boolean) isAlreadyInTheFetchQueue:(Feed *)feed;
- (void) fetchPosts:(Feed *)feed;
- (void) createPostInFeed:(Feed*)feed withTitle:(NSString *)title withContent:(NSString *)content withURL:(NSString *)url withDate:(NSDate *)date;
Now here's the init method:
Note if I set the _childManagedObjectContext's parent here, the program crashes.
-(AsyncFetchEngine *)init
{
_rssParserQueue = dispatch_queue_create("com.example.MyQueue", NULL);
_uRLsToFetch = [[NSMutableArray alloc] initWithCapacity:32];
_childManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_childManagedObjectContext setPersistentStoreCoordinator:[_managedObjectContext persistentStoreCoordinator]];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:#selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:_childManagedObjectContext];
return self;
}
- (void)contextDidSave:(NSNotification*)notification
{
void (^mergeChanges) (void) = ^ {
[_managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
};
if ([NSThread isMainThread]) {
mergeChanges();
} else {
dispatch_sync(dispatch_get_main_queue(), mergeChanges);
}
}
Fetch method:
Note: not sure which MOC to use to determine localFeed, _managedObjectContext crashes the app.
- (void) fetchPosts:(Feed *)feed
{
if (!_childManagedObjectContext.parentContext) {
[_childManagedObjectContext setParentContext:self.managedObjectContext];
}
if ([self isAlreadyInTheFetchQueue:feed]) {
NSLog(#"AsyncFetchEngine::fetchPosts> \"%#\" is already in the fetch queue", feed.name);
return;
}
[_uRLsToFetch addObject:feed];
NSURL *url=[NSURL URLWithString:feed.rss];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
if (![NSURLConnection canHandleRequest:req]) {
return;
}
Feed *localFeed = ((Feed *)[_childManagedObjectContext existingObjectWithID:[feed objectID] error:nil]);
dispatch_async(_rssParserQueue, ^{
NSLog(#"AsyncFetchEngine::fetchPosts> Opening %#", feed.rss);
[RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems)
{
for(RSSItem *i in feedItems)
{
[self createPostInFeed:localFeed withTitle:i.title withContent:(i.content?i.content:i.itemDescription) withURL:[i.link absoluteString] withDate:(i.pubDate?i.pubDate:[NSDate date])];
}
NSLog(#"AsyncFetchEngine::fetchPosts> Found %d items", [feedItems count]);
[_uRLsToFetch removeObject:feed];
}
failure:^(NSError *error)
{
NSLog(#"AsyncFetchEngine::fetchPosts> RSSParser lost it: %#", [error localizedDescription]);
}];
});
}
- (Boolean) isAlreadyInTheFetchQueue:(Feed *)feed
{
Feed *f=nil;
for (f in _uRLsToFetch) {
if ([f isEqual:feed]){
return YES;
}
}
return NO;
}
NSFecthedResultsController, do I need it that way?
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
// Note: I originally tried to use the main MOC here, but it also used to crash the app.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Post" inManagedObjectContext:_childManagedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
/* NSPredicate *predicate =[NSPredicate predicateWithFormat:#"feed.rss LIKE '%#'", _detailItem.rss];
[fetchRequest setPredicate:predicate]; */
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
_fetchedResultsController = aFetchedResultsController;
return _fetchedResultsController;
}
It usually crashes somewhere in this method, according to the dump stack.
If it doesn't crash, I have my post added to a (null) Category...
- (void)createPostInFeed:(Feed*)feed withTitle:(NSString *)title withContent:(NSString *)content withURL:(NSString *)url withDate:(NSDate *)date
{
[_childManagedObjectContext performBlockAndWait:^{
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Error in refetch: %#",[error localizedDescription]);
abort();
}
}];
NSLog(#"AsyncFetchEngine.h: Searching similar posts among %d", [[self.fetchedResultsController fetchedObjects] count]);
Boolean found=NO;
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"title == %# AND url == %# AND feed == %#", title, url, feed];
NSArray *similarPosts = [_fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:predicate];
if ([similarPosts count] > 0)
{
NSLog(#"\n\n\n\t\tAsyncFetchEngine::fetchPosts> Skipping %# (%#)", title, url);
} else {
NSLog(#"\n\n\n\t\tAsyncFetchEngine::fetchPosts> Putting new post in %#", feed.name);
NSEntityDescription *postEntityDescription = [NSEntityDescription entityForName:#"Post"
inManagedObjectContext:_childManagedObjectContext];
[_childManagedObjectContext performBlock:^{
Post *initPost = (Post *)[[NSManagedObject alloc]
initWithEntity:postEntityDescription
insertIntoManagedObjectContext:_childManagedObjectContext];
initPost.title = title;
initPost.url = url;
initPost.excerpt = content;
initPost.date = date;
initPost.read = nil;
initPost.feed = feed;
NSError *error;
if (![_childManagedObjectContext save:&error])
{
NSLog(#"[createPost] Error saving context: %#", error);
}
NSLog(#"Created: %# (%#)", title, url);
//[[NSNotificationCenter defaultCenter] postNotificationName:#"NewPostAdded" object:self];
}];
}
}
So, my questions are:
When I have multiple MOCs, do I fetch from the main and write to a child?
How should I respectivelly use these above?
Thanks!
Answering my own question for the sake of eventually helping another newbie.
Check NSOperationQueue with Coredata.
There's a very good example here.
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.
I myself have found a solution to the problem.
-(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