How to completely remove CoreData from xcode project - ios

I'm trying to remove CoreData completely from my app because I have accidentally deleted the model and despite trying to fix it, I keep getting:
Cannot create an NSPersistentStoreCoordinator with a nil model
Since I'm not using CoreData for this project, I decided to try to remove it entirely, but I'm having trouble. Here is what I've done so far:
Removed Import statements for CoreData framework and deleted from project
Removed all CoreData code from the AppDelegate
Removed the Model from "Copy Bundle Resources" in Build Phases
Restarted computer, reinstalled xcode SDK 8.4
Gone through the project folders to double check if I deleted them instead of just removing the reference.
And yet I'm still getting the error. Any help would be greatly appreciated as I can't run my app. The Build phase works fine, but at startup, I get this error:
'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'
*** First throw call stack:
(0x182b8822c 0x1947fc0e4 0x1828192a0 0x1001543a4 0x100151580 0x1004a0fd4 0x1004a0f94 0x1004abdb8 0x1004a42c4 0x1004ae5d4 0x1004b0248 0x19505921c 0x195058ee0)
libc++abi.dylib: terminating with uncaught exception of type NSException
I understand that it is detecting a nil Model, so how do I remove CoreData entirely from the project?
My AppDelegate File:
//
// AppDelegate.m
// Oingo
//
// Created by Matthew Acalin on 4/24/15.
// Copyright (c) 2015 Oingo Inc. All rights reserved.
//
#import "AppDelegate.h"
#import <Parse/Parse.h>
#import "PFTwitterUtils+NativeTwitter.h"
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#import <TwitterKit/TwitterKit.h>
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#interface AppDelegate ()
#end
#implementation AppDelegate
- (id)initWithCoder:(NSCoder *)aDecoder {
[Fabric with:#[CrashlyticsKit]];
return self;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// [NSThread sleepForTimeInterval:5];
// Initialize Parse.
[Parse enableLocalDatastore];
[Parse setApplicationId:#"xxx"
clientKey:#"xxx"];
[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions];
[PFTwitterUtils initializeWithConsumerKey:#"xxx" consumerSecret:#"xxxx"];
//Initialize Twitter
[[Twitter sharedInstance] startWithConsumerKey:#"xxxxx" consumerSecret:#"xxxx"];
[Fabric with:#[[Twitter sharedInstance]]];
[Fabric with:#[TwitterKit, CrashlyticsKit]];
// [Optional] Track statistics around application opens.
//[PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
//Initialize Facebook
[FBSDKAppEvents activateApp];
return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}
//Method added for facebook integration
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (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 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.
[FBSDKAppEvents activateApp];
}
- (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 "Oingo.Oingo" 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:#"Oingo" 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:#"Oingo.sqlite"];
// 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
Screenshot of Preferences/Location settings: Derived data = relative
Screenshot of output:

Related

+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'AppData'

The persistant container goes nil. When I run program I get this error : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'AppData'
I have found similar questions on stackoverflow but haven't got any problem solving answer that is why I'm posting this question again.
Here is my code :
-(void)saveData
{
NSManagedObjectContext *localContext=((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
// [self initPer];
// UIApplication *app = [UIApplication sharedApplication];
// AppDelegate *delg = (AppDelegate *)app.delegate;
// NSManagedObjectContext *localContext = delg.getManagedObj;
// AppData *appData1= [NSEntityDescription insertNewObjectForEntityForName:#"AppData" inManagedObjectContext:localContext];
// NSManagedObjectContext *localContext = _del.persistentContainer.viewContext;
AppData *appDta = [NSEntityDescription insertNewObjectForEntityForName:#"AppData" inManagedObjectContext:localContext];
NSString *value = [valueArray1 componentsJoinedByString:#" "];
NSString *commandKey = [keyArray1 componentsJoinedByString:#" "];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:value forKey: nsDate];
NSLog(#"%#", dictionary);
appDta.key = commandKey;
appDta.details = dictionary;
}
AppDelegate.h :
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong) NSPersistentContainer *persistentContainer;
- (void)saveContext;
-(NSManagedObjectContext*)getManagedObj;
#end
AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
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 invalidate graphics rendering callbacks. 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 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 {
// 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];
}
-(NSManagedObjectContext*)getManagedObj{
return self.persistentContainer.viewContext;
}
#pragma mark - Core Data stack
#synthesize persistentContainer = _persistentContainer;
- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
#synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:#"Model"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(#"Unresolved error %#, %#", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context 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();
}
}
You can see that some lines are commented, I kept it to show that I've also tried it but haven't got any result.
As mentioned HERE
Set
AppDelegate.h :
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong) NSPersistentContainer *persistentContainer;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSManagedObjectContext *)getManagedObj;
AppDelegate.m :
#pragma mark - Core Data stack
#synthesize persistentContainer = _persistentContainer;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
#synthesize managedObjectModel = _managedObjectModel;
- (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 (_managedObjectContext != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Model.sqlite"];
NSLog(#"DB Path==> %#",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 *)getManagedObj {
// 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] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
Then try with your commented code like as under :
AppDelegate *objAppDel = (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [objAppDel managedObjectContext];
AppData *objAppData = [NSEntityDescription insertNewObjectForEntityForName:#"AppData" inManagedObjectContext:context];

-[__NSArrayM objectAtIndex:]: index 9 beyond bounds for empty array'

I am currently using CoreData and trying to fetch the data with a NSFetchedResultsController.
But the app crashes at the following line
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#the app crashes here
id sectionInfo = [[self.fetchedRequestController sections]objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
with the error message: -[__NSArrayM objectAtIndex:]: index 9 beyond bounds for empty array'.
Before you are telling me that the array empty is, i know that but how do if populate it?
I don't know where I got wrong and none of the other questions were able to help.
AppDelgate.m is just copy and paste from the core Data preset.
Just in case it matters:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
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
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "controwl.a" 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:#"trackingData" 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:#"timetracking.sqlite"];
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
And the TableViewClass where the fetchedResultsController is called.
#import "FirstTableViewController.h"
#interface FirstTableViewController ()
#end
#implementation FirstTableViewController
#synthesize fetchedRequestController = _fetchedRequestController;
#synthesize managedObjectContext = _managedObjectContext;
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error;
if (![[self fetchedRequestController]performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1);
}
self.title = #"Customer Names";
_managedObjectContext = [(AppDelegate*)[[UIApplication sharedApplication]delegate] managedObjectContext];
NSManagedObject* customer;
customer = [NSEntityDescription insertNewObjectForEntityForName:#"Customer" inManagedObjectContext:_managedObjectContext];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSFetchedResultsController *)fetchedRequestController {
if (_fetchedRequestController != nil) {
return _fetchedRequestController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Customer" inManagedObjectContext:_managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:#"nam" cacheName:#"Root"];
self.fetchedRequestController = theFetchedResultsController;
_fetchedRequestController.delegate = self;
return _fetchedRequestController;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id sectionInfo = [[self.fetchedRequestController sections]objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (void)configureCell:(UITableViewCell*)cell atIndexPath:(NSIndexPath *)indexPath {
UIViewController *customer = [_fetchedRequestController objectAtIndexPath:indexPath];
cell.textLabel.text = #"test";
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 10;
}
- (void)viewDidUnload {
self.fetchedRequestController = nil;
}
#end
Your implementation of numberOfSectionsInTableView: says that there are 10 sections. What your crash is telling you is that this is not true. The table view asks the delegate how many sections it should have, then asks for details on each section. If you return the wrong number of sections, the table view asks for details on nonexistent sections.
You should not hard code the number of sections. The documentation for NSFetchedResultsController provides a sample implementation that's probably what you need:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.fetchedRequestController sections] count];
}

[UINavigationController setManagedObjectContext:]: unrecognized selector sent to instance

I know it has been asked multiple times, but the answers won't help solve my problem.
First of all I'm making a Tab based app with CoreData wich opens upon the press of a Button a TableViewController.
The main.storyboard file in case it matters:
http://www.pictureupload.de/originals/pictures/200215153130_Screen_Shot_2015-02-20_at_15.24.09.png
Everything works fine and it saves the data into the Database, but if I try to Display them in a TableViewController it suddenly crashes
(-[UINavigationController setManagedObjectContext:]: unrecognized selector sent to instance 0x79092b80).
AppDelgate.m is just copy and paste from the core Data preset.
Just in case it matters:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
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
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "controwl.a" 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:#"trackingData" 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:#"timetracking.sqlite"];
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
The TableViewController gets called by FirstViewController by the btnBarAdd function:
FirstViewController.m
#implementation FirstViewController
#synthesize context = _context;
- (void)viewDidLoad {
[super viewDidLoad];
_context = [(AppDelegate*)[[UIApplication sharedApplication]delegate] managedObjectContext];
}
- (IBAction)btnBarAdd:(id)sender {
[self performSegueWithIdentifier:#"FirstTableViewSegue" sender:sender];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"FirstTableViewSegue"]) {
[[segue destinationViewController] setManagedObjectContext:_context];
}
}
#end
Any help is appreciated!
The segue links FirstViewController to the Navigation Controller, so the destinationViewController of the segue is the UINavigationController. Hence when you try to set the managedObjectContext on destinationViewController, you get the error.
You need instead to use the topViewController property of the navigation controller, to access the FirstTableViewController itself:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"FirstTableViewSegue"]) {
UINavigationController *navCtrl = (UINavigationController *)[segue destinationViewController];
// Assuming the class of your table view controller is "FirstTableViewController"....
// You will need to import the relevant .h file
FirstTableViewController *tableVC = (FirstTableViewController *)navCtrl.topViewController;
[tableVC setManagedObjectContext:_context];
}
}
Check if destination view controller for your code
[[segue destinationViewController] setManagedObjectContext:_context];
Has property or method to assign context. Seems like you are calling UINavigationController with segue but it does not have such property to handle context
Reset the simulator and run it again.
You might have added new properties to the entities, you should delete the app each time you make changes to core data entities.

iOS Local Notification Action in Background

I'm building an application that when a user receives a local notification it charges their credit card via stripe and parse, there is more to it then that but thats the start. When the notification is received inside the app everything works fine but when the notification is received outside the app the action is not complete.
https://github.com/jackintosh7/Wake
I would the action to be complete outside the app and also a view to be brought up when the user clicks on the notification.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
if (StripePublishableKey) {
[Stripe setDefaultPublishableKey:StripePublishableKey];
}
if (ParseApplicationId && ParseClientKey) {
[Parse setApplicationId:ParseApplicationId
clientKey:ParseClientKey];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"Customer Created"]) {
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:#"Home"];
self.window.rootViewController = viewController;
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Customer Created"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:#"Tutorial"];
self.window.rootViewController = viewController;
}
[self.window makeKeyAndVisible];
UILocalNotification *notification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
[self application:application didReceiveLocalNotification:notification];
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(#"1");
// 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
{
// 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]) {
// 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();
}
}
}
#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;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"AlarmModel" withExtension:#"mom"];
_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 = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"AlarmModel.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.
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:
#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES}
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;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
});
NSString *customerId = #"cus_4ot6ggKUOp6bHg";
NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
[self chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];
NSLog(#"11");
}
-(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{
NSLog(#"22");
[PFCloud callFunctionInBackground:#"chargeCustomer"
withParameters:#{
#"amount":amountInCents,
#"customerId":customerId
}
block:^(id object, NSError *error) {
//Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
handler(object,error);
}];
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
Action:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Wake" message:notification.alertBody delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
NSString *customerId = #"cus_4ot6ggKUOp6bHg";
NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
[AppDelegate chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];
NSLog(#"11");
}
+(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{
NSLog(#"22");
[PFCloud callFunctionInBackground:#"chargeCustomer"
withParameters:#{
#"amount":amountInCents,
#"customerId":customerId
}
block:^(id object, NSError *error) {
//Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
handler(object,error);
}];
}
Result of nslogs you added:
See the charge information:(null)
Error:invalid_request_error: No such customer: cus_4ot6ggKUOp6bHg (Code: 141, Version: 1.4.1)
The last one I understand what the issue is.
when your app is running application:didReceiveLocalNotification: is calling, but if your App is not running, the information about the local notifications is added to launchOptions dict;
In your AppDelegate, in application:didFinishLaunchingWithOptions add this code:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Keep al exist code in your app...and at the END of this methods
UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
[self application:application didReceiveLocalNotification:localNotification];
}
return YES;
}
It´s good thing to force the UIAlert in the main thread,:
dispatch_async(dispatch_get_main_queue(),
^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Wake" message:notification.alertBody delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
});
New Proposal:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
NSString *customerId = #"cus_4ot6ggKUOp6bHg";
NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
[self chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];
});
}
And :
-(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{
[PFCloud callFunctionInBackground:#"chargeCustomer"
withParameters:#{
#"amount":amountInCents,
#"customerId":customerId
}
block:^(id object, NSError *error) {
//Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
handler(object,error);
NSLog(#"See the error:%#",[error localizedDescription]);
NSLog(#"See the charge information:%#",[object description]);
}];
}

iCloud takes very long to connect to local store and iCloud Changes to the context done affect my fetchedResultsController

When my app loads it give that notification that its using local store: 1 usually it takes 4 to 5 minutes before it returns using local store :0. Not only that reloading using NSNotifications does not seem to work although going to a new view then back does.
appDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"firstTime"]){
UIAlertView *msg = [[UIAlertView alloc] initWithTitle:#"Would You Like to Keep Clients Synced With iCloud" message:nil delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
msg.tag = 101;
[msg show];
}
[self registerForiCloudNotifications];
UINavigationController *nc = (UINavigationController *)self.window.rootViewController;
ClientListViewController *iC = (ClientListViewController *)[nc viewControllers][0];
iC.context = [self managedObjectContext];
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
{
// 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]) {
// 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();
}
}
}
#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] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_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;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Benjii" withExtension:#"momd"];
_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;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:[self storeOptions] 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.
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:
#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES}
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;
}
-(NSURL *)storeURL{
return [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Benjii.sqlite"];
}
- (void)registerForiCloudNotifications{
NSLog(#"Registering");
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:#selector(storesWillChange:)
name:NSPersistentStoreCoordinatorStoresWillChangeNotification
object:self.persistentStoreCoordinator];
[notificationCenter addObserver:self
selector:#selector(storesDidChange:)
name:NSPersistentStoreCoordinatorStoresDidChangeNotification
object:self.persistentStoreCoordinator];
[notificationCenter addObserver:self
selector:#selector(persistentStoreDidImportUbiquitousContentChanges:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:self.persistentStoreCoordinator];
}
#pragma mark - iCloud Support
//Use these options in your call to addPersistentStore:
-(NSDictionary *)storeOptions{
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:#"GraniteCloudStore" forKey:NSPersistentStoreUbiquitousContentNameKey];
return options;
}
- (void) persistentStoreDidImportUbiquitousContentChanges:(NSNotification *)changeNotification{
NSManagedObjectContext *context = self.managedObjectContext;
[context performBlock:^{
[context mergeChangesFromContextDidSaveNotification:changeNotification];
}];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Reload" object:nil];
}
- (void) storesWillChange:(NSNotification *)notification {
NSManagedObjectContext *context = self.managedObjectContext;
[context performBlockAndWait:^{
NSError *error;
if([context hasChanges]){
BOOL success = [context save:&error];
if(!success && error){
//perform error handling
NSLog(#"%#", [error localizedDescription]);
}
}
[context reset];
}];
//Refresh User Interface
NSLog(#"Stores will change");
}
-(void)storesDidChange:(NSNotification *)notification{
//Refresh your User Interface
NSLog(#"Stores did change");
[[NSNotificationCenter defaultCenter] postNotificationName:#"Reload" object:nil];
}
-(void)migrateiCloudStoreToLocalStore{
//assuming you only have one store.
NSPersistentStore *store = [[_persistentStoreCoordinator persistentStores] firstObject];
NSMutableDictionary *localStoreOptions = [[self storeOptions] mutableCopy];
[localStoreOptions setObject:#YES forKey:NSPersistentStoreRemoveUbiquitousMetadataOption];
NSPersistentStore *newStore = [_persistentStoreCoordinator migratePersistentStore:store
toURL:[self storeURL]
options:localStoreOptions
withType:NSSQLiteStoreType
error:nil];
[self reloadStore:newStore];
}
-(void)reloadStore:(NSPersistentStore *)store {
if(store){
[_persistentStoreCoordinator removePersistentStore:store error:nil];
}
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self storeURL]
options:[self storeOptions]
error:nil];
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#pragma mark - Alert View Delegate
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if(alertView.tag == 101){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"firstTime"];
if(buttonIndex != alertView.cancelButtonIndex){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"iCloudSupport"];
}
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
#end
and fetchresultcontroller:
-(NSFetchedResultsController *)clientResultsController{
if(clientResultsController != nil){
return clientResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Client"];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name beginswith %#"];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"finitial" ascending:YES selector:#selector(localizedCompare:)];
//[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSFetchedResultsController *theFetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:#"finitial"
cacheName:#"Root"];
self.clientResultsController = theFetchedResultController;
self.clientResultsController.delegate = self;
return clientResultsController;
}
and observer in view Controller:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserverForName:#"Reload"
object:self
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note){
NSLog(#"Reloading");
[self reloadFetchedResults:note];
}];
}
Sorry if the answer is really simple i checked the other similar questions and they were either unanswered or Outdated (though I tried a couple of them anyway). Any help will be much appreciated
edit
it seems like my observer isnt catching the observerForName:#"Reload"
does anyone know how to add an observer to the method that sends this message:
PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:: CoreData: Ubiquity: mobile~843477F1-43D0-4E72-BD91-26C3276A9212:GraniteCloudStore
Using local storage: 0
also noticed that if I wait until the above message then rotate the screen also causes table to populate however the persistentStoreCoordinatorDidChange is called before that notice
I'm having a similar issue here, but in my case, when I migrate my app from a non-icloud version to an iCloud version, the existing data does not show. Though if I add a new entry, then everything shows and with a debugging, I realised why everything is showing.
In my UITableView, I did the following:
- (void)reloadFetchedResults:(NSNotification*)note {
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (note)
{
[self.timelineTableView reloadData];
}
}
In my viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadFetchedResults:) name:#"RefetchAllDatabaseData" object:[[UIApplication sharedApplication] delegate]];
// In your case, the name would be Reload
- (void)viewDidUnload
{
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Try this - I'm a complete noob here but this worked for me to be able to see changes straight away.

Resources