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];
}
Related
I am working on Objective-C with CoreData, i am getting below error...
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class
'NSManagedObject' must have a valid NSEntityDescription.'
I added CoreData to my project. I created saveData method in viewControllerA and i called it in viewControllerB.
In this scenario I am getting error, if I call saveData method in viewDidLoad of viewControllerA it's working properly.
In AppDelegate.h
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
In AppDelegate.m
#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 "com.brninfotech._607_introToCoreDataFinal" 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:#"VehicleNumberDataBase" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (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;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"VehicleNumberDataBase.sqlite"];
// NSLog(#"StoreURL is %#",storeURL);
NSError *error = nil;
NSString *failureReason = #"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = #"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:#"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_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();
}
}
}
in viewControllerA viewDidLoad
self.ad = (AppDelegate *)[[UIApplication sharedApplication]delegate];
self.VehicleNumberED = [NSEntityDescription entityForName:#"VehicleNumberEntity" inManagedObjectContext:self.ad.managedObjectContext];
- (void)saveData {
NSManagedObject * managedObj = [[NSManagedObject alloc]initWithEntity:self.VehicleNumberED insertIntoManagedObjectContext:self.ad.managedObjectContext];
[managedObj setValue:self.textFieldString forKey:#"vehicleNumberAtt"];
NSError * errorObj;
[self.ad.managedObjectContext save:&errorObj];
if (errorObj) {
NSLog(#"Something goes wrong");
}else {
NSLog(#"Saved Successfully");
}
NSFetchRequest * fetReq = [NSFetchRequest fetchRequestWithEntityName:#"VehicleNumberEntity"];
NSError * fetchErrorObj;
self.storedDataArray = [self.ad.managedObjectContext executeFetchRequest:fetReq error:&fetchErrorObj];
NSLog(#"array count is %lu", self.storedDataArray.count);
for (int i=0; i<self.storedDataArray.count; i++) {
self.storedManagedObj = [self.storedDataArray objectAtIndex:i];
self.vehicleNumberArray = [self.storedManagedObj valueForKey:#"vehicleNumberAtt"];
}
NSLog(#"Vehicle number is : %#", [self.storedManagedObj valueForKey:#"vehicleNumberAtt"]);
}
in ViewVontrollerB
- (IBAction)saveVehicleNumberButton:(UIButton *)sender {
VehicleDetailsViewController *vedvc = [[VehicleDetailsViewController alloc]init];
vedvc = [self.storyboard instantiateViewControllerWithIdentifier:#"VeDVC"];
vedvc.textFieldString = self.vehicleNumberTextField.text;
[vedvc saveData];
[self.navigationController pushViewController:vedvc animated:YES];
}
The issue here is that you are executing [vedvc saveData] before displaying the vedvc view controller. At this point, vedvc has not been displayed, so its viewDidLoad has not yet been executed. Consequently self.ad and self.VehicleNumberED are both nil. Hence the error: the entity description is nil.
The simplest fix would be to move the initialisation of those two variables (ad and VehicleNumberED) to the saveData method. But you might do better to rethink your code structure.
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.
I am modifying an existing Core Data app to iCloud. My problem is that when I try to load seed data after detecting an initial app launch in the appDelegate, my first [NSEntityDescription insertNewObjectForEntityForName: inManagedObjectContext:] statement throws the error "'NSInvalidArgumentException', reason: '+entityForName:XXX nil is not a legal NSManagedObjectContext parameter searching for entity name 'XXX''" I'm sure the inManagedObjectContext parameter I'm passing is the correct one, but sure enough, it's nil in debugger.
Part of my trouble is that I don't understand what cues the app to call the boilerplate core data -managedObjectContext, -managedObjectModel, and -persistentStoreCoordinators methods. The app always seemed to call the methods and instantiate these objects automatically whenever they were required.
The core data stack is basically the standard stuff from a core data app template, with the iCloud option added to persistentStoreCoordinator, and a branch for migrating existing data. Here's the code; trying to limit it to essential elements:
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Notification registrations
[self register_iCloudNotifications];
// Data from defaults
BOOL _firstLocalLaunch = ...
BOOL _update =
BOOL _iCLoudDataSeeded = ...
// FIRST APP LAUNCH LOCALLY; FIRST iCLOUD LAUNCH ANYWHERE
// This is the code that's calling initializeSeedData and getting the error
if (_firstLocalLaunch && !_iCloudDataSeeded) {
[self initializeSeedData];
... update defaults
} else if {
... code for update launch and normal launch
// Safety check for seed data in persistent store; if none, initialize.
NSFetchRequest *modelFetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *modelEntity = [NSEntityDescription entityForName:#"entity" inManagedObjectContext:self.managedObjectContext];
[modelFetchRequest setEntity:modelEntity];
NSArray *fetchResults = [_managedObjectContext executeFetchRequest:modelFetchRequest error:nil];
if (!fetchResults.count) {
NSLog(#"Safety catch: seed data missing");
[self initializeSeedData];
}
return YES;
}
- (void)initializeSeedData
{
SWSEntity *entity1 = [NSEntityDescription insertNewObjectForEntityForName:#"Entity" inManagedObjectContext:_managedObjectContext]; // THIS IS WHATS THROWING THE ERROR
entity.name = #"First seed data item";
[_managedObjectContext save:nil];
}
- (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:#"model" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
NSLog(#"exists; returning");
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// NO UPDATE FROM PREVIOUS
if (!_update) {
NSLog(#"Persistent store: adding");
[self add_iCloudPersistentStore];
// UPDATE FROM PREVIOUS VERSION
} else {
NSLog(#"Persistent store: migrating");
...code for migrating existing store to iCloud; not called with this issue
}
return _persistentStoreCoordinator;
}
- (void)add_iCloudPersistentStore
{
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self get_iCloudStoreURL]
options:[self iCloudPersistentStoreOptions]
error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
- (NSDictionary *)iCloudPersistentStoreOptions
{
return #{NSPersistentStoreUbiquitousContentNameKey: #"myAppStore",
NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES};
}
Interesting thing: If I comment out the [self initializeSeedData] after detecting a first launch, the "safety catch" for adding the data executes, and creates the seed data just fine! The only thing I can figure that's different is that I'm executing a fetchRequest on the managed object context first... somehow the _managedObjectContext is instantiated when the fetch is executed, and still around for [self initializeSedData]. Why would that happen?
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.
there's not much to say, i have done another application for core data everything went always fine.
This application is giving a weird error.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Ingredient''
*** First throw call stack:(0x1faa012 0x13e7e7e 0x10edf57 0x1134052 0x3211 0x11a04b 0x2fe2 0x22c1 0x19157 0x19747 0x1a94b 0x2bcb5 0x2cbeb 0x1e698 0x1f05df9 0x1f05ad0 0x1f1fbf5 0x1f1f962 0x1f50bb6 0x1f4ff44 0x1f4fe1b 0x1a17a 0x1bffc 0x20dd 0x2005)
vlibc++abi.dylib: terminate called throwing an exception
i tried to simplify my app using only the app delegate and a mainViewController, in the MainViewController i tried to add an pbject to my Coredata just to see if everithing is working. This is my model
App delegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
MasterViewController *masterViewController = [[MasterViewController alloc]initWithNibName:#"MasterViewController" bundle:nil];
masterViewController.managedObjectContext = self.managedObjectContext;
[self.window setRootViewController:masterViewController];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (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:#"pizzaCoreData" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"pizzaCoreData.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;
}
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
TableIngredientsViewController *tableIngredientVC = [[TableIngredientsViewController alloc]init];
TablePizzasViewController *tablePizzaVC = [[TablePizzasViewController alloc]init];
NSManagedObject *newPizza = [NSEntityDescription insertNewObjectForEntityForName:#"Ingredient" inManagedObjectContext:_managedObjectContext];
[newPizza setValue:#"TIMIDA" forKey:#"name"];
NSError *error;
if (![_managedObjectContext save:&error]){
NSLog(#"Error %# %#", error, [error userInfo]);
}
UINavigationController *ingredientNavController = [[UINavigationController alloc]initWithRootViewController:tableIngredientVC];
UINavigationController *pizzaNavController = [[UINavigationController alloc]initWithRootViewController:tablePizzaVC];
[self setViewControllers:#[pizzaNavController, ingredientNavController]];
}
This is a screenshot of the model:
http://tinypic.com/view.php?pic=97nrcn&s=5
i have updated my AppDelegate, i forgot copy last methods
Your _managedObjectContext is nil when you are doing this
NSManagedObject *newPizza = [NSEntityDescription insertNewObjectForEntityForName:#"Ingredient" inManagedObjectContext:_managedObjectContext];
So before passing your context to a view controller make sure it is initialized properly.
You have to take your managedObjectContext from your appDelegate. So in your MainController instead of:
_managedObjectContext
use:
((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext