Issue CoreData Migration - iphone

I have an App with two sqlite databases and two xcdatamodel´s. So every things fine, except if i want to change or add some properties to one of the models.
I am creating a new model version and make my changes to that. After Setting the current model version, i start my app and get following Exception:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
I have the following Manager for my CoreData Operations:
#interface CoreDataManager ()
#property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (strong, nonatomic) NSManagedObjectContext *mainQueueContext;
#property (strong, nonatomic) NSManagedObjectContext *privateQueueContext;
#end
#implementation CoreDataManager
+ (instancetype)defaultStore
{
static CoreDataManager *_defaultStore = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_defaultStore = [self new];
});
return _defaultStore;
}
#pragma mark - Singleton Access
+ (NSManagedObjectContext *)mainQueueContextWithDB:(NSString *)db
{
return [[self defaultStore] mainQueueContextWithDB:db];
}
+ (NSManagedObjectContext *)privateQueueContextWithDB:(NSString *)db
{
return [[self defaultStore] privateQueueContextWithDB:db];
}
+ (NSManagedObjectID *)managedObjectIDFromString:(NSString *)managedObjectIDString
{
return [[[self defaultStore] persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:managedObjectIDString]];
}
#pragma mark - Lifecycle
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contextDidSavePrivateQueueContext:)name:NSManagedObjectContextDidSaveNotification object:[self privateQueueContext]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contextDidSaveMainQueueContext:) name:NSManagedObjectContextDidSaveNotification object:[self mainQueueContext]];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Notifications
- (void)contextDidSavePrivateQueueContext:(NSNotification *)notification
{
#synchronized(self) {
[self.mainQueueContext performBlock:^{
[self.mainQueueContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
}
- (void)contextDidSaveMainQueueContext:(NSNotification *)notification
{
#synchronized(self) {
[self.privateQueueContext performBlock:^{
[self.privateQueueContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
}
#pragma mark - Getters
- (NSManagedObjectContext *)mainQueueContextWithDB:(NSString *)db
{
actualDB = db;
if (!_mainQueueContext) {
_mainQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_mainQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _mainQueueContext;
}
- (NSManagedObjectContext *)privateQueueContextWithDB:(NSString *)db
{
actualDB = db;
if (!_privateQueueContext) {
_privateQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_privateQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _privateQueueContext;
}
#pragma mark - Stack Setup
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (!_persistentStoreCoordinator) {
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self persistentStoreURL] options:[self persistentStoreOptions] error:&error]) {
NSLog(#"Error adding persistent store. %#, %#", error, error.userInfo);
}
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
- (NSURL *)persistentStoreURL
{
return [[NSFileManager appLibraryDirectory] URLByAppendingPathComponent:actualDB];
}
- (NSDictionary *)persistentStoreOptions
{
return #{NSInferMappingModelAutomaticallyOption: #YES, NSMigratePersistentStoresAutomaticallyOption: #YES};
}
#end

You may try to change the journal_mode to DELETE (guess WAL is default in Core Data on iOS 7 and higher ?!?). The persistent store options which i use and having no trouble with dozens of data model changes is:
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
#{#"journal_mode" : #"DELETE"}, NSSQLitePragmasOption, nil];
I hope it helps ...
About Journal Mode on http://www.sqlite.org/pragma.html:
"The DELETE journaling mode is the normal behavior. In the DELETE mode, the rollback journal is deleted at the conclusion of each transaction. Indeed, the delete operation is the action that causes the transaction to commit. (See the document titled Atomic Commit In SQLite for additional detail.)"

Related

No data in SQLite [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this book about Core Data. I am on my second chapter and there's an ongoing project that I followed. The project adds an Organization, and three employees. One of the employee is a leader. I have successfully followed the steps, although there are 4 warnings but it doesn't have an error. I know this should work because I had this same project before I reinstall my OSX.
AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
//Core Data Implementation
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
//Display Person
- (void)readData;
- (void)displayPerson:(NSManagedObject *)person withIndentation:(NSString *)indentation;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createData];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark - Create Data
-(void)createData
{
NSManagedObject *organization = [NSEntityDescription insertNewObjectForEntityForName:#"Organization" inManagedObjectContext:self.managedObjectContext];
[organization setValue:#"Company, Inc." forKey:#"name"];
[organization setValue:[NSNumber numberWithInt:[#"Company, Inc." hash]] forKey:#"id"];
NSManagedObject *john = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[john setValue:#"John" forKey:#"name"];
[john setValue:[NSNumber numberWithInt:[#"John" hash]] forKey:#"id"];
NSManagedObject *jane = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[jane setValue:#"Jane" forKey:#"name"];
[jane setValue:[NSNumber numberWithInt:[#"Jane" hash]] forKey:#"id"];
NSManagedObject *bill = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[bill setValue:#"Bill" forKey:#"name"];
[bill setValue:[NSNumber numberWithInt:[#"Bill" hash]] forKey:#"id"];
NSMutableSet *johnsEmployees = [john mutableSetValueForKey:#"employees"];
[johnsEmployees addObject:jane];
[johnsEmployees addObject:bill];
}
- (void)saveContext {
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Core01" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Core01.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#pragma mark - Display Person
- (void)displayPerson:(NSManagedObject*)person withIndentation:(NSString*)indentation {
NSLog(#"%#Name: %#", indentation, [person valueForKey:#"name"]);
indentation = [NSString stringWithFormat:#"%# ", indentation];
NSSet *employees = [person valueForKey:#"employees"];
id employee;
NSEnumerator *it = [employees objectEnumerator];
while ((employee = [it nextObject]) != nil) {
[self displayPerson:employee withIndentation:indentation];
}
}
- (void)readData {
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *orgEntity = [NSEntityDescription entityForName:#"Organization" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:orgEntity];
NSArray *organizations = [context executeFetchRequest:fetchRequest error:nil];
id organization;
NSEnumerator *it = [organizations objectEnumerator];
while ((organization = [it nextObject]) != nil) {
NSLog(#"Organization: %#", [organization valueForKey:#"name"]);
NSManagedObject *leader = [organization valueForKey:#"leader"];
[self displayPerson:leader withIndentation:#" "];
}
}
- (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:.
}
#end
These are the only codes that are important to the project. Yes, this is a very simple Core Data app.
There's a guide in the book to access the database by using sqlite3.
In Terminal.app:
Input: cd ~/Library/Application\ Support/iPhone\ Simulator
Input: find . -name "Core01.sqlite" –print
Output: ./6.0/Applications/25DB9FAD-6921-4791-9409-FF84F275D8A8/Documents/Core01.sqlite
Input: sqlite3 ./6.0/Applications/25DB9FAD-6921-4791-9409-FF84F275D8A8/Documents/Core01.sqlite
In sqlite3:
Input: sqlite> select Z_PK, ZID, ZLEADER, ZNAME from ZORGANIZATION;
Output: 1|-19904|2|Company, Inc.
Input: sqlite> select Z_PK, ZID, Z2EMPLOYEES, ZNAME from ZPERSON;
Output:
1|6050|2|Jane
2|-28989||John
3|28151|2|Bill
The problem is, the database is empty. Idk what went wrong, nor what I miss.
I think the problem is that you need to call the method -(void)saveContext after you set all the data in -(void)createData
Try this:
-(void)createData
{
NSManagedObject *organization = [NSEntityDescription insertNewObjectForEntityForName:#"Organization" inManagedObjectContext:self.managedObjectContext];
[organization setValue:#"Company, Inc." forKey:#"name"];
[organization setValue:[NSNumber numberWithInt:[#"Company, Inc." hash]] forKey:#"id"];
NSManagedObject *john = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[john setValue:#"John" forKey:#"name"];
[john setValue:[NSNumber numberWithInt:[#"John" hash]] forKey:#"id"];
NSManagedObject *jane = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[jane setValue:#"Jane" forKey:#"name"];
[jane setValue:[NSNumber numberWithInt:[#"Jane" hash]] forKey:#"id"];
NSManagedObject *bill = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[bill setValue:#"Bill" forKey:#"name"];
[bill setValue:[NSNumber numberWithInt:[#"Bill" hash]] forKey:#"id"];
NSMutableSet *johnsEmployees = [john mutableSetValueForKey:#"employees"];
[johnsEmployees addObject:jane];
[johnsEmployees addObject:bill];
[self saveContext];
}
Unless I missed it in the code, you call [self createData]; but never save the context.
At the end of your createData method, add in the [self saveContext]; call.

Facebook in iPhone app

I am working on an iPhone app,in this i have an option for sharing my posts with face book(i am just passing the user id of facebook user and my server side developer do the posting part)
I am able to take the user id while log in in face book
But problem is-after the user authenticate from facebook,"post on your behalf" is not coming in the app
(i am using ios6 SDK)
(i have created my app in facebook with checked that public_action from graph)
I have gone through the tutorials(scrumptious) given in facebook developer page,but could not make it
Here are my code-If any one find the error or missing part,please help me to clear that
AppDelegate.h
#import <FacebookSDK/FacebookSDK.h>
#class ViewController;
#interface AppDelegate : UIResponder
#property (strong, nonatomic) FBSession *session;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#property (strong,nonatomic) IBOutlet UINavigationController *navBar;
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#define APP_ID #"fd725FDE45a44198a5b8ad3f7a0ffa09"
#implementation AppDelegate
#synthesize session = _session;
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [self.session handleOpenURL:url];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_location",
#"user_birthday",
#"user_likes",
#"email",
#"publish_action",
nil];
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
default:
break;
}
}
#end
InviteFriendViewController.h
#interface InviteFriendViewController :
-(IBAction)fbfrnds:(id)sender;
- (void)updateView;
#end
InviteFriendViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"userid"];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (!appDelegate.session.isOpen) {
appDelegate.session = [[FBSession alloc] init];
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}
];
}
}
}
-(void)facebookReteriveInformation:(NSDictionary *)dictnry{
FriendlistViewController *friends = [[FriendlistViewController alloc]initWithNibName:#"FriendlistViewController" bundle:nil];
friends.token = string;
[self.navigationController pushViewController:friends animated:YES];
}
-(IBAction)fbfrnds:(id)sender{
sharedClass=[SharedClass sharedInstance];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[self updateView];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}];
}
NSLog(#"string issss %#",string);
}
- (void)updateView {
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSLog(#"string issss %#",string);
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
} else {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
}
}
-(void)dataFetching:(NSString*)strng1{
NSURL *url = [NSURL URLWithString:strng1];
ProfileConnector *obj = [[ProfileConnector alloc] init];
obj.delegate1 = self;
[obj parsingJson:url];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
} else {
action();
}
}
}
#end
Since you're using the 3.1 version of Facebook SDK, openActiveSessionWithPermissions:allowLoginUI:completionHandler: is not supposed to be used and the old way of doing it does not seem to be functional anymore; from the 3.1 migration documentation;
...you will need to remove usage of openActiveSessionWithPermissions:allowLoginUI:completionHandler: and replace it with openActiveSessionWithReadPermissions:allowLoginUI:completionHandler: (or even more simply, openActiveSessionWithAllowLoginUI).
Later, when your app needs to publish back to Facebook, you should use reauthorizeWithPublishPermissions:defaultAudience:completionHandler: to seek the additional permissions.
Even more details available at the migration docs.

Error in iPhone core data

My AppDelegate.h:
#import <UIKit/UIKit.h>
#import "Child.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, retain, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSString *)applicationDocumentsDirectory;
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m:
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
NSLog(#"Error");
}
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
// Explicitly write Core Data accessors
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"iSalahProject.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
#end
My controller implementation class where entity is being created and I am getting the error:
-(IBAction)addChildren:(id)sender{
inputChildName = nameOfChild.text;
NSManagedObjectContext *context = [app managedObjectContext];
Child * childrenName = [NSEntityDescription insertNewObjectForEntityForName:#"Child" inManagedObjectContext:context];
childrenName.name = inputChildName;
}
The error I am getting is:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Child''
I am using iOS-5 XCode 4.2 ARC. Please help me resolving this issue, I already have spent hours resolving it, but I couldn't find any solutions.
Your application is terminating because your managedObjectContext is nil. Check for it and if its nil copy it from delegate. You can use this if condition in your -(IBAction)addChildren:(id)sender method
if (managedObjectContext == nil)
{
managedObjectContext = [(CoreDataBooksAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
}
Following are the possibilities for this error to occur:
Typo in the Entity name.
Nil managed object context object.
Failure to add the model containing the entity to the persistent
store the context uses.
Failure to add the correct persistent store to the context itself.

Starting Xcode Project From Scratch and cannot showing anything

I am following a book (Big Nerd Ranch IOS Programming) and the version of my xcode that I am using is slightly newer than the one that the book uses. As a consequence, I cannot exactly follow the books steps and one of those steps is to create a window-based application.
What I did was: I created an empty project which gives me the delegate and a few other files. I created my own MainWindow.xib.
I kept on reading and I am at the part where I need to compile and I am supposed to see something on the simulator. However, I do not see anything. I know that I am missing something here, because I am guessing that I have not wired up the MainWindow.xib correctly with the code (??). Note that the book told me to add map view, text field, and activity indicator to the main window.
I am wondering what is the proper way to get a project started from scratch. I actually prefer doing it this way so that I can get the lowdown of starting a ios project.
UPDATE:
After I set the Info.plist "Main nib file base name" to "MainWindow". I was able to see the view. However, I cannot click on the text field on the simulator and make the keyboard show up. I clicked the home button and when I tried clicking on the icon again, It would show white screen and not the map with text field over it.
WhereamiAppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface WhereamiAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>{
CLLocationManager * locationManager;
IBOutlet MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UITextField *locationTitleField;
}
#property (strong, nonatomic) IBOutlet UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
WhereamiAppDelegate.m
#import "WhereamiAppDelegate.h"
#implementation WhereamiAppDelegate
#synthesize window = _window;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
[worldView setShowsUserLocation:YES];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"%#", newLocation);
}
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"Could not find location: %#", error);
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the active 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
{
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"whereami" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"whereami.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
main.m
#import <UIKit/UIKit.h>
#import "WhereamiAppDelegate.h"
int main(int argc, char *argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([WhereamiAppDelegate class]));
}
}
See here (quoted from #WrightCS):
MainWindow.xib is the defined in your info.plist as the Main nib file
base name. In your MainWindow.xib, you define the first controller
that you want to load, in your case, RootViewController.
Check your main.m file (assuming you have one - if not, that's part of your problem). You'll probably see a line like this:
int retVal = UIApplicationMain(argc, argv, nil, nil);
For your app to do anything, it should be something like this:
int retVal = UIApplicationMain(argc, argv, #"UIApplication", #"MyAppDelegate");
Assuming you have MyAppDelegate.h and MyAppDelegate.m in your project.

View in PersistenceCoreDataViewController.xib won't display

Yes, I'm a newbie, but I'd sure appreciate some help. I've got a fairly simple example app I'm working through in an effort to learn about Core Data. I've got a app that simply displays four text fields and allows a user to save text in those four fields.
The app compiles, but upon execution I get a "black" screen. I had initially assumed my problem was that my view in my PersitenecCoreDataViewController.xib wasn't displaying for some reason. However, in my debugger console I've found where my app is being terminated due to an uncaught exception:
NSInvalidArgumentException', reason:
'executeFetchRequest:error: A fetch
request must have an entity
I'm now thinking I'm not setting up my fetch request properly.
I've got my app delegate and viewController classes code listed below. Thanks in advance for your time and assistance. . .
// PersistenceCoreDataAppDelegate.h
// Created by RICHARD COLEMAN on 3/21/11.
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#class PersistenceCoreDataViewController;
#interface PersistenceCoreDataAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow* window;
PersistenceCoreDataViewController* rootController;
#private
NSManagedObjectContext* managedObjectContext_;
NSManagedObjectModel* managedObjectModel_;
NSPersistentStoreCoordinator* persistentStoreCoordinator_;
}
#property (nonatomic, retain) IBOutlet UIWindow* window;
#property (nonatomic, retain, readonly) NSManagedObjectContext* managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel* managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator* persistentStoreCoordinator;
#property (nonatomic, retain) IBOutlet PersistenceCoreDataViewController* rootController;
- (NSString *)applicationDocumentsDirectory;
#end
// PersistenceCoreDataAppDelegate.m
// Created by RICHARD COLEMAN on 3/21/11.
#import "PersistenceCoreDataAppDelegate.h"
#import "PersistenceCoreDataViewController.h"
#implementation PersistenceCoreDataAppDelegate
#synthesize window;
#synthesize rootController;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[window addSubview:rootController.view];
[window makeKeyAndVisible];
return YES;
}
// applicationWillTerminate: saves changes in the application's managed object context // before the application terminates.
- (void)applicationWillTerminate:(UIApplication *)application {
NSError *error = nil;
if (managedObjectContext_ != nil) {
if ([managedObjectContext_ hasChanges] && ![managedObjectContext_ save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark -
#pragma mark Core Data stack
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"PersistenceCoreData" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"PersistenceCoreData.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
}
#pragma mark -
#pragma mark Applications Documents directory
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
}
- (void)dealloc {
[managedObjectContext_ release];
[managedObjectModel_ release];
[persistentStoreCoordinator_ release];
[window release];
[super dealloc];
}
#end
// PersistenceCoreDataViewController.h
// Created by RICHARD COLEMAN on 3/21/11.
#import <UIKit/UIKit.h>
#interface PersistenceCoreDataViewController : UIViewController {
UITextField* line1;
UITextField* line2;
UITextField* line3;
UITextField* line4;
}
#property (nonatomic, retain) IBOutlet UITextField* line1;
#property (nonatomic, retain) IBOutlet UITextField* line2;
#property (nonatomic, retain) IBOutlet UITextField* line3;
#property (nonatomic, retain) IBOutlet UITextField* line4;
#end
// PersistenceCoreDataViewController.m
// Created by RICHARD COLEMAN on 3/21/11.
#import "PersistenceCoreDataViewController.h"
#import "PersistenceCoreDataAppDelegate.h"
#implementation PersistenceCoreDataViewController
#synthesize line1;
#synthesize line2;
#synthesize line3;
#synthesize line4;
- (void)applicationWillTerminate:(NSNotification *)notification {
// Get a reference to our application delegate, which we then use to get the managed object context,
// i.e. context, that was created for us
// Remember an application delegate performs a specific action at a certain predefined time on behalf
// of the application
PersistenceCoreDataAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [appDelegate managedObjectContext];
NSError* error;
// Loop to execute 4x, ie. once for each line
for (int i = 1; i <= 4; i++) {
// Obtain field name by appending value of i to line
NSString* fieldName = [NSString stringWithFormat:#" line%d", i];
// Obtain reference to the correct field
UITextField* theField = [self valueForKey:fieldName];
// Create fetch request; remember a fetch request is just a predefined query
NSFetchRequest* request = [[NSFetchRequest alloc] init];
// Create entity description (describing Line entity using correct context we retrieved
// from application delegate) that will be fed to fetch request so it knows what type
// of entity to look for
NSEntityDescription* entityDescription = [NSEntityDescription entityForName:#" Line"
inManagedObjectContext:context];
[request setEntity:entityDescription];
// Create a predicate that identifies the right object for the field (this will help us
// find out if there is already a managed object in the persistent store that corresponds
// to this field
// managed object - instance of entity
// persistent store - area where managed objects exist
NSPredicate* pred = [NSPredicate predicateWithFormat:#"(lineNum = %d)", i];
[request setPredicate:pred];
// Declared pointer and set to nil b/c we don't know yet if we're going to load a managed object
// from the persistent store or create a new one
NSManagedObject* theLine = nil;
// Actually exec the fetch against the given context; rememeber the fetch request is just a query
// and the context is where we manage the state, access, info about properties, etc.
NSArray* objects = [context executeFetchRequest:request error:&error];
// Checking to see if objects are nil; if nil there was an error; handle appropriately
if (objects == nil) {
NSLog(#" There was an error!");
// Do whatever error handling is appropriate
}
// Was an object returned that matched our criteria; if there is one, load it; if not create one
if ([objects count] > 0)
theLine = [objects objectAtIndex:0];
else
theLine = [NSEntityDescription insertNewObjectForEntityForName:#" Line"
inManagedObjectContext:context];
// use key-value coding to set the line number and text for this managed object
[theLine setValue:[NSNumber numberWithInt:i] forKey:#" lineNum"];
[theLine setValue:theField.text forKey:#" lineText"];
[request release];
}
// looping is complete, save changes
[context save:&error];
}
// this method needs to determine if there is any existing data and if so, load it
- (void)viewDidLoad {
// get a reference to the application delegate and use it to get a pointer to the application's
// default context
PersistenceCoreDataAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [appDelegate managedObjectContext];
// Create an Entity Description that describes our entity
NSEntityDescription* entityDescription = [NSEntityDescription entityForName:#" Line"
inManagedObjectContext:context];
// Create a fetch request, i.e. a query, and pass it the entity description so it knows what type
// of objects to retriev
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// We don't create a predicate as we want to retrieve all Line objects in the persistent store
NSError* error;
NSArray* objects = [context executeFetchRequest:request error:&error];
// Ensure we get back a valid array
if (objects == nil) {
NSLog(#" There was an error!");
// Do whatever error handling is appropriate
}
// Using fast enumeration to loop thru array of retrieved managed objects pulling out the lineNum
// and lineText and updating one of the text fields on our user interface
for (NSManagedObject* oneObject in objects) {
NSNumber* lineNum = [oneObject valueForKey:#" lineNum"];
NSString* lineText = [oneObject valueForKey:#" lineText"];
NSString* fieldName = [NSString stringWithFormat:#" line%#", lineNum];
UITextField* theField = [self valueForKey:fieldName];
theField.text = lineText;
}
[request release];
// Register to be notified when the app is about to terminate so you can save any changes the user
// has made to the data
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:app];
[super viewDidLoad];
}
// Override to allow orientations other than the default portrait orientation.
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.line1 = nil;
self.line2 = nil;
self.line3 = nil;
self.line4 = nil;
[super viewDidUnload];
}
- (void)dealloc {
[line1 release];
[line2 release];
[line3 release];
[line4 release];
[super dealloc];
}
#end
# Julien and fluchtpunkt.. I am pretty new too and I was wondering if there being a space there cause problems??
I may be wrong but seeing your error message " fetch request must have an entity" made me wonder if you did create the entity and the related attributes you want using core data? that is the first thing that comes to my mind.. let me know..