Search code examples
objective-ccocoa-touchioscore-datacgrect

iOS CGRectOffset and Core Data Issues


I know this doesn't make any sense, but I'm getting a really strange error in an iPhone App I am building using Core Data and calling CGRectOffset. My App Delegate's didFinishLaunchingWithOptions method looks like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

// Setup the Managed Object Context
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
    // Do something - Like exit
}

//Load up the database form a pList
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"tJournals" ofType:@"plist"];
NSMutableArray *plistJournals = [NSMutableArray arrayWithContentsOfFile:plistPath];

//Create a bunch of journals
for (NSDictionary *journal in plistJournals) {
    [TJournal journalWithDictionary:journal inManagedObjectContext:context];
}

NSError *error = nil;
[context save:&error];

// ------ Create the View Controller ------
// The Scrolling List
JournalListVC *jvc = [[JournalListVC alloc] init];

// Adjust for the Status Bar's height
CGRect viewFrame = CGRectOffset(jvc.view.frame, 0.0, 20.0);
jvc.view.frame = viewFrame;

jvc.managedObjectContext = context;

// Add the View Controller to the screen
[self.window addSubview:jvc.view];
[self.window makeKeyAndVisible];

return YES;
}

Currently, the app crashes with the following error when I leave the CGRect viewframe line in:

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'TJournal''"

If I comment out the CGRect line, it runs fine. The call inside the for loop executes just fine (it write's data to a Core Data DB entity names TJournal, and does exactly what it's supposed.) Obviously, there is no dependence on Core Data for CGRectOffset, so I'm guessing this error is spurious. But I can't, for the life of me, figure it out.

I've tried cleaning all targets, wiping out the database in the simulator, etc. But nothing seems to work.

Any ideas? Thanks!


Solution

  • Note that when you reference jvc.view.frame, it is dynamically loading jvc’s view. If the contents of the view (or xib!) have a dependency on a managed object context when it’s loaded, that could produce the error.

    Try moving the jvc.managedObjectContext = context; line to right after JournalListVC *jvc = [[JournalListVC alloc] init];.

    (PS: your view shouldn’t have to account for the status bar; instead, your UIWindow should do it, and then your view controller’s view’s frame should just be the window’s bounds.)