Core Data model Is throwing Exception - iphone

I am using core data in my app. My app was working fine.. I recently reset my simulator setting and now that app is throwing exception. I read all posts and clean my target also but it is not running ,,then I set breakPoint and found exception in last line of this code
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"TouristGuide" withExtension:#"momd"];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
This code is in my APPdelegate file.. And Exception is
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an
NSPersistentStoreCoordinator with a nil model'

As the error says, the model seems to be nil, or rather the modelURL. You can see this by adding NSLog(#"%#", modelURL), it will print (null).
Make sure that your model is really called TouristGuide and is in the mainBundle, i.e. gets added when building.

Related

NSManagedObjectMOdel fails to initialize on iOS 5 and above

I have a project which works fine when I build it for iOS 4.x, however it fails when I build it for iOS 5.x with a crash. To clarify, the 4.x build will run fine on iOS 5.1, however when I build against 5.0 or 5.1, I get the crash described below.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel == nil)
{
__managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; //crash
}
return __managedObjectModel;
}
I checked the docs, and supposedly supplying nil as for the parameter is supposed to default to the main bundle. Anyone know if anything that changed with CoreData that would cause this to happen?
For what it's worth, I've run the "Analyze" tool and no memory leaks or anything unusual is being reported.
I've managed to come up with a work around. I created a new single-view project and then copied the generated code to initialize the managed object model into my new project. My hunch is that that [[NSManagedObjectModel mergedModelFromBundles:nil] works differently in the iOS 5.1 SDK and perhaps it wasn't able to find my data model as it wasn't stored in the project root but a separate "Data" folder.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"PreferencesModel" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
You don't actually describe the crash or provide any error messages but the following StackOverflow question has a solution to a crash that may help:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil

SIGABRT Error After Snippets Added to Source Code

So after adding the following snippets to my source code, the application refuses to run and gives me a SIGABRT error:
CIALBrowserViewController.h
UIBarButtonItem *homeButtonItem;
CIALBrowserViewController.m
#interface CIALBrowserViewController ()
- (void)goHome:(id)sender;
..
homeButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"home.png"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(goHome:)] autorelease];
..
- (void)goHome:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://google.ca/"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}
The SIGABRT Error
2012-06-17 14:15:15.130 CIALBrowser[1753:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(0x354fa88f 0x378a1259 0x3544f1d7 0x5f8b 0x32f67c17 0x2a67 0x32f66cab 0x32f607dd 0x32f2eac3 0x32f2e567 0x32f2df3b 0x370ed22b 0x354ce523 0x354ce4c5 0x354cd313 0x354504a5 0x3545036d 0x32f5f86b 0x32f5ccd5 0x28df 0x2878)
terminate called throwing an exception(lldb)
Heres the full source code to CIALBrowserViewController.m: http://pastebin.com/uuUgi7Dc
In else section of if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad), there is no homeButtonItem alloced or inited, so homeButtonItem is nil. Then [buttons addObject:homeButtonItem]; will crash, because you are adding a nil object to array.
THe SIGABRT error suggests that somewhere in your code you use the method insertObject:atIndex: and use nil as the first parameter, which is not allowed, throwing an error. I went to your code on paste bin and did not see that method called there, so the error is likely in another file.
Hope this helps!

Core Data: Not able to add persistent store to coordinator

I am making an app that displays organisms based around certain properties, such as Name, Color, Weight, etc. but those properties won't be known until run time. Which is why I am creating the NSManagedObjectModel programmatically. It seems I am able to initialize the model properly, as I use NSLog statement to show the organism entity's properties. But when I call the method:
[orgPersistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]
It returns NO and I am getting an error in my persistent store coordinator method that says:
"Could not add persistent store:The operation couldn’t be completed. (Cocoa error 256.)"
I have tried turning these options on, but I still got the same error:
NSString * const NSMigratePersistentStoresAutomaticallyOption;
NSString * const NSInferMappingModelAutomaticallyOption;
Here is the full code:
- (NSPersistentStoreCoordinator *)orgPersistentStoreCoordinator {
if (orgPersistentStoreCoordinator != nil) {
return orgPersistentStoreCoordinator;
}
NSURL *storUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:#"organisms.sqlite"]];
NSError *error = nil;
orgPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self orgManagedObjectModel]];
NSLog(#"Entities: %#",[[self orgManagedObjectModel] entities]);
if (![orgPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
NSLog(#"Could not add persistent store:%#",[error localizedDescription]);
}
return orgPersistentStoreCoordinator;
}
And here is a snippet of how I am creating the ManagedObjectModel programmatically.
+ (NSManagedObjectModel *) orgManagedObjectModel
{
FieldGuide *f = [FieldGuide sharedFieldGuide];
NSManagedObjectModel *orgModel = [[NSManagedObjectModel alloc]init];
NSEntityDescription *organismEntity = [[NSEntityDescription alloc]init];
[organismEntity setName:#"OrganismCoreData"];
[organismEntity setManagedObjectClassName:#"OrganismCoreData"];
[orgModel setEntities:[NSArray arrayWithObject:organismEntity]];
NSMutableArray *orgEntityProperties = [[NSMutableArray alloc]init];
// 1. Name attributes
for (NameParameter *n in f.nameAttributes)
{
NSAttributeDescription *nameAttr = [[NSAttributeDescription alloc]init];
[nameAttr setName:n.name];
[nameAttr setAttributeType:NSStringAttributeType];
[orgEntityProperties addObject:nameAttr];
}
[organismEntity setProperties:orgEntityProperties];
return orgModel;
}
Finally, when I try to insert some organisms and save via the NSManagedObjectContext, the app terminates and displays this in the log:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
Any help or directions would be greatly appreciated, thanks!
Edit:
And yes, I have tried deleting the app from the simulator, clean target, and deleting the organisms.sqlite from the documents folder via finder.
Edit #2:
I forgot to add that the addPersistentStore method also returns another error:
2012-04-30 14:13:46.109 biodex[7510:14803] CoreData: error: (1) I/O error for database at /Users/junryandelacruz/Library/Application Support/iPhone Simulator/5.1/Applications/ACE957AF-2FC0-4EAF-B226-5019F70FAB90/Documents/organisms.sqlite. SQLite error code:1, 'near "OR": syntax error'
Looks like there is a mistake in your storeURL. This is the "Unknown File Read Error", usually to do with the path to the file.
From the documentation:
NSFileReadUnknownError = 256,
The second error certainly has nothing to do with adding the persistent store. Check your code for the "OR" predicate.

core data in a ios static library

I created a static library for iOS. The library uses core data to store some objects fetched from the internet.
When I try to use my library in a standard iOS project, it seems like it can't create any instances of core data entities. I have the following error :
-[NSManagedObject initWithDictionary:]: unrecognized selector sent to instance 0x6e5d4e0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject initWithDictionary:]: unrecognized selector sent to instance 0x6e5d4e0'
initWithDictionary is actually a method I call on a core data entity object.
Then I tried to create the managed object model out of the library like shown here : core data in a static library for the iPhone
NSMutableSet *allBundles = [[[NSMutableSet alloc] init] autorelease];
[allBundles addObjectsFromArray: [NSBundle allBundles]];
[allBundles addObjectsFromArray: [NSBundle allFrameworks]];
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles: [allBundles allObjects]];
OR
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
but it didn't work. I have the following error when I try to instantiate a class of my library giving it the managed object model :
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LauncherViewController initWithNibName:managedObjectModel:andKey:]: unrecognized selector sent to instance 0x6b94db0'
If I try this : core data in a static library for the iPhone , I get this error :
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Please help me, I really don't know what to do anymore...

Why can't I get the context from the delegate with this code?

I get an annoyingly vague error from the following code:
GFree2AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
context = [delegate managedObjectContext];
context is defined as a NSManagedObjectContext in the .h file and is the same in the delegate. All the right files seem to be included (except for <CoreData/CoreData.h> in the .m file - but the program throws the same issue whether its included or not. Its included in the header file.)
All the correct frameworks and stuff are included - when I started the project I selected "use coredata to manage data" or whatever it was. So surely there shouldn't be a problem?
Is there a better way to do what I'm trying to do? Basically I don't want to have to keep passing the context through different classes till I eventually want to use it (storing data is such a small part of my application).
In the console the error I get is:
2010-08-28 13:09:24.726 GFree2[3912:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
...
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
If I comment out the line: context = [delegate managedObjectContext]; then it all seems to work fine. (at the moment I haven't acctually used any coredata or anything so theres no more code related to it.
Thanks for anyone who can help, or provide some insight into this - its so complicated.
Edit: my app delegate file methods:
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"GFree" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"GFree.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the path to the application's Documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
EDIT AGAIN:
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"GFree" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
is the line where the error is. I'm not sure what type of file this is, but I'm sure it's obviously not finding it or something... :/ any ideas what I'm supposed to do?
#kiamlaluno - sorry for rolling back your edits, didn't mean to, just curious to see what you'd changed and thought that would show me... but it just completely removed them apparently. lol.
Edit build results:
DataModelCompile build/Debug-iphonesimulator/GFree2.app/GFree2.mom GFree2.xcdatamodel
cd "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2"
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/momc -XD_MOMC_TARGET_VERSION=10.6 "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/GFree2.xcdatamodel" "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/build/Debug-iphonesimulator/GFree2.app/GFree2.mom"
I believe that the problem is in persistentStoreCoordinator method in your GFree2AppDelegate.m file.
Could you update your question with the exact code of managedObjectModel, managedObjectContext and persistentStoreCoordinator methods from this file?
These methods are generated by the XCode when you check "Use Core Data for storage".
By the way, you shouldn't import .m files.
You're getting the error because GFree.momd doesn't exist. From the docs for NSURL's pathForResource:ofType: method:
Return Value The full pathname for the resource file or nil if the file could not be located.
GFree.momd is generated at build time from your .xcdatamodeld file (look in the Build Results for the line starting DataModelVersionCompile and expand it). Have you deleted or renamed that file?
Is it still listed in the Compile Sources section of your build target? (In Xcode expand Targets / [AppName] / Compile Sources).
Just noticed that your debug log says the app is called GFree2 but your code's looking for GFree.momd. Did you rename the project? If the data model file is now called GFree2.xcdatamodeld then you need to change the line that imports the momd file to use the new GFree2 name, too.