I build my TabBar programmatically and based on if the User is loggedIn, I set
[self.window setRootViewController:home];
Here is the code I call in:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
if (![Persistence loggedIn])
{
[self showLoginScreen];
}
else
{
SignupBase *login = [STLoginSignupBase new];
[login loginUserwithUsername:[Persistence username] andPassword:[Persistence authPass] requestByNewUser:NO completionBlock:^(NSError *error)
{
if (!error)
{
[login loginSuccess];
[self showTabBarScreen];
}
else
{
[STAlertViewUtils showAlert:#"" :error.localizedDescription :kButtonTitleDismiss];
[self showLoginScreen];
}
}];
}
-(void)showTabBarScreen
{
dispatch_async(dispatch_get_main_queue(), ^{
TabBarVC *tabBarVC = [[TabBarVC alloc]init];
[self.window setRootViewController:tabBarVC];
});
}
-(void)showLoginScreen
{
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"STLoginSignup" bundle:nil];
HomeVC *homeVC = (HomeVC *)[storyboard instantiateViewControllerWithIdentifier:[HomeVC storyboardID]];
UINavigationController *home = [[UINavigationController alloc]initWithRootViewController:homeVC];
[self.window setRootViewController:home];
});
}
In the TabBar, the first tab "Inbox" is a tableViewController managed with NSFetchedResultsController. When I launch the app for the first time, all the objects are fetched and displayed in the tableView beautifully; however, when I logout and login back in, and "Inbox" is reloaded, I get a blank tableView. Zero objects are fetched locally and even if RESTkit fetches objects, they don't appear in the tableView. When I stop the app in the simulator and relaunch it, all the objects are fetched locally and remotely, and appear in the tableView as they should!
Here is how I logout from the Profile tab (different tab):
- (void)logoutWithCompletionBlock:(void(^)(void))completionBlock
{
[Persistence setLoggedInStatus:NO];
RKObjectManager *objectManager = [self getObjectManager];
[objectManager.HTTPClient clearAuthorizationHeader];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = delegate.managedObjectStore.mainQueueManagedObjectContext;
[managedObjectContext reset];
[delegate deregisterWithUrbanAirship];
if (completionBlock)
{
completionBlock();
}
}
After I log back in the App, "Inbox" tab viewController is loaded again.
In my "Inbox" loadView which gets called, I have the following code:
- (void)loadView
{
[self getManagedObjectFromAppDelegate]
}
- (void)getManagedObjectFromAppDelegate
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate setupCoreDataWithRESTKit];
self.objectManager = [self getObjectManager];
self.objectManager.managedObjectStore = appDelegate.managedObjectStore;
self.objectManager.managedObjectStore.managedObjectCache = appDelegate.managedObjectStore.managedObjectCache;
self.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;
}
This is the code in [AppDelegate setupCoreDataWithRESTKit];
- (RKManagedObjectStore *)setupCoreDataWithRESTKit
{
NSError * error;
NSURL * modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"App" ofType:#"momd"]];
NSManagedObjectModel * managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
self.managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
[self.managedObjectStore createPersistentStoreCoordinator];
NSArray * searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentPath = [searchPaths objectAtIndex:0];
NSPersistentStore * persistentStore = [self.managedObjectStore addSQLitePersistentStoreAtPath:[NSString stringWithFormat:#"%#/App%#.sqlite", documentPath, [Persistence username]] fromSeedDatabaseAtPath:nil withConfiguration:nil options:[self optionsForSqliteStore] error:&error];
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
NSLog(#"Path: %#", [NSString stringWithFormat:#"%#/App%#.sqlite", documentPath, [Persistence username]]);
if(!persistentStore){
NSLog(#"Failed to add persistent store: %#", error);
}
[self.managedObjectStore createManagedObjectContexts];
return self.managedObjectStore;
}
Please note that each user has a different .sqlite file loaded based on their username: i.e. AppUserName. So when I logout and log back in if it's a same user, then the same file is created/loaded. If it's a different user, then a different name file is created/loaded.
Question: Why does NSFetchedResultsController displays an empty tableView after I logout and log back in, but it works fine when I launch the app the first time?
*EDIT *
I changed and tried the code below but the problem persists:
- (void)logoutWithCompletionBlock:(void(^)(void))completionBlock
{
[Persistence setLoggedInStatus:NO];
RKObjectManager *objectManager = [self getObjectManager];
[objectManager.HTTPClient clearAuthorizationHeader];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = delegate.managedObjectStore.mainQueueManagedObjectContext;
[self clearManagedObjectContext:managedObjectContext];
[delegate deregisterWithUrbanAirship];
if (completionBlock)
{
completionBlock();
}
}
- (void)clearManagedObjectContext:(NSManagedObjectContext*)managedObjectContext
{
NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:#"EntityA" inManagedObjectContext:managedObjectContext]];
NSMutableArray *result = [NSMutableArray arrayWithArray:[managedObjectContext executeFetchRequest:fetch error:nil]];
for (id entityA in result)
{
[managedObjectContext deleteObject:entityA];
}
[result removeAllObjects];
[fetch setEntity:[NSEntityDescription entityForName:#"EntityB" inManagedObjectContext:managedObjectContext]];
result = [NSMutableArray arrayWithArray:[managedObjectContext executeFetchRequest:fetch error:nil]];
for (id entityB in result)
{
[managedObjectContext deleteObject:entityB];
}
[result removeAllObjects];
[fetch setEntity:[NSEntityDescription entityForName:#"EntityC" inManagedObjectContext:managedObjectContext]];
result = [NSMutableArray arrayWithArray:[managedObjectContext executeFetchRequest:fetch error:nil]];
for (id entityC in result)
{
[managedObjectContext deleteObject:entityC];
}
[result removeAllObjects];
[managedObjectContext saveToPersistentStore:nil];
}
You shouldn't be doing [managedObjectContext reset]; unless you tear down the persistent store that is backing the main thread context (so, tear down the whole Core Data stack and destroy the SQLite file).
Either correct this or just loop over the things you want to delete in the context and save the changes up to the (parent) persistent context.
Related
I have an old code (mostly written in 2014-2015), and I need to update it as painless as possible.
First part:
NSManagedObjectContext *parentContext = [NSManagedObjectContext MR_contextForCurrentThread];
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithParent:parentContext];
it says:
'MR_contextForCurrentThread' is deprecated: This method will be
removed in MagicalRecord 3.0
I was trying to implement solutions from the internet, but none of it helped me.
Second part:
(IBAction)addButtonAction:(id)sender {
NSString *title = #"";
AppActionSheet *actionSheet = [AppActionSheet actionSheet];
[actionSheet setButtonWithTitle:AppLocalizedString(#"eventsCreateMenuCreateEvent") block:^{
[self actionSheetCreateNewEventDidSelected];
}];
[actionSheet showInView:self.view];
}
- (void)actionSheetCreateNewEventDidSelected {
NSManagedObjectContext *context = [NSManagedObjectContext MR_context];
AppEvent *event = [AppEvent MR_createEntityInContext:context];
AppContact *contact = [[AppUserSettings shared] authorizedUserInContext:context];
[event.participantsSet addObject:contact];
[event.activeParticipantsSet addObject:contact];
event.owner = contact;
event.modificationDate = [NSDate date];
AppEventContact *item = [AppEventContact MR_createEntityInContext:context];
item.contact = contact;
item.event = event;
item.index = #0;
AppAddEventViewController *addEventVC = [[UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil]
instantiateViewControllerWithIdentifier:#"AppAddEventViewController"];
addEventVC.delegate = self;
addEventVC.context = context;
addEventVC.event = event;
[self.navigationController pushViewController:addEventVC animated:YES];
}
The AddButton opens list of buttons, and one from the list is supposed to open view CreateNewEvent.
While debugging, when I press CreateEvent it stops on 4th string but doesn't forward to [self actionSheetCreateNewEventDidSelected];
And third one and the last:
[managedContext lock];
[managedContext reset];
//delete the store from the current managedObjectContext
if ([[managedContext persistentStoreCoordinator] removePersistentStore:[[[managedContext persistentStoreCoordinator] persistentStores] lastObject] error:&error]) {
// remove the file containing the data
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
//recreate the store like in the appDelegate method
[[managedContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error];
}
[managedContext unlock];
which complains at lock and unlock, but it would be incorrect to simply delete these two strings (anyways theyre not working anymore, and app seems to be working)?
I'm considering to rewrite everything to swift, but hope theres way to fix it for now.
And thanks in advance!
I need help to integrate iCloud to my CoreData.
I have tried many changes on AppDelegate, but only Error:
"libc++abi.dylib: terminating with uncaught exception of type NSException"
I have a TeamID and a Developer Account.
AppDelegate:
//
// AppDelegate.m
// ToolDB
//
// Created by Patrick Gottberg on 01.07.14.
//
//
#import "AppDelegate.h"
#import "PersonsTVC.h"
#import "RolePersonsTVC.h"
#import "MaterialPersonsTVC.h"
#import "RolesTVC.h"
#import "MaterialsTVC.h"
#import "PersonsTVC.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
#synthesize fetchedResultsController = __fetchedResultsController;
- (void)insertRoleWithRoleName:(NSString *)roleName
{
Role *role = [NSEntityDescription insertNewObjectForEntityForName:#"Role"
inManagedObjectContext:self.managedObjectContext];
role.name = roleName;
[self.managedObjectContext save:nil];
}
- (void)insertMaterialWithMaterialName:(NSString *)materialName
{
Material *material = [NSEntityDescription insertNewObjectForEntityForName:#"Material"
inManagedObjectContext:self.managedObjectContext];
material.name = materialName;
[self.managedObjectContext save:nil];
}
- (void)insertPersonWithPersonfirstname:(NSString *)personfirstname
{
Person *person = [NSEntityDescription insertNewObjectForEntityForName:#"Person"
inManagedObjectContext:self.managedObjectContext];
person.firstname = personfirstname ;
person.surname= #"Example";
[self.managedObjectContext save:nil];
}
- (void)importCoreDataDefaultRoles {
NSLog(#"Importing Core Data Default Values for Roles...");
[self insertRoleWithRoleName:#"DMG Mori DMU 70 "];
[self insertRoleWithRoleName:#"Kunzmann BA 800"];
NSLog(#"Importing Core Data Default Values for Roles Completed!");
}
- (void)importCoreDataDefaultMaterials {
NSLog(#"Importing Core Data Default Values for Materials...");
[self insertMaterialWithMaterialName:#"S235"];
[self insertMaterialWithMaterialName:#"26Mo2"];
[self insertMaterialWithMaterialName:#"1.2316"];
[self insertMaterialWithMaterialName:#"C16"];
NSLog(#"Importing Core Data Default Values for Materials Completed!");
}
- (void)importCoreDataDefaultPersons {
NSLog(#"Importing Core Data Default Values for Persons...");
[self insertPersonWithPersonfirstname:#"Square"];
[self insertPersonWithPersonfirstname:#"T-Slot"];
[self insertPersonWithPersonfirstname:#"Ball"];
[self insertPersonWithPersonfirstname:#"Shell"];
NSLog(#"Importing Core Data Default Values for Persons Completed!");
}
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = #"Role"; // Put your entity name here
NSLog(#"Setting up a Fetched Results Controller for the Entity named %#", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:#"Person.name = Blah"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self.fetchedResultsController performFetch:nil];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Set the application defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:#"YES"
forKey:#"myKeyName"];
[defaults registerDefaults:appDefaults];
[defaults synchronize];
[self setupFetchedResultsController];
if (![[self.fetchedResultsController fetchedObjects] count] > 0 ) {
NSLog(#"!!!!! ~~> There's nothing in the database so defaults will be inserted");
[self importCoreDataDefaultRoles];
[self importCoreDataDefaultMaterials];
[self importCoreDataDefaultPersons];
}
else {
NSLog(#"There's stuff in the database so skipping the import of default data");
}
// TAB BAR
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
NSLog(#"I'm an iPad");
// *** Set up the Persons Split Views (2-Way Delegation & Pass Managed Object Context) *** //
// Set up SPLIT VIEW for Persons
UISplitViewController *splitViewController = [[tabBarController viewControllers] objectAtIndex:0];
// Set up Split View MASTER view for Persons
UINavigationController *personsMasterTVCnav = [splitViewController.viewControllers objectAtIndex:0];
splitViewController.delegate = (id)personsMasterTVCnav.topViewController;
PersonsTVC *personsTVC = [[personsMasterTVCnav viewControllers] objectAtIndex:0];
personsTVC.managedObjectContext = self.managedObjectContext;
// Set up Split View DETAIL view for Persons
UINavigationController *personsDetailTVCnav = [splitViewController.viewControllers objectAtIndex:1];
PersonDetailTVC *personDetailTVC = [personsDetailTVCnav.viewControllers objectAtIndex:0];
// Set up MASTER and DETAIL delegation so we can send messages between views
personsTVC.delegate = personDetailTVC;
personDetailTVC.delegate = personsTVC;
// *** Set up the Roles Views *** (Pass Managed Object Context)//
UINavigationController *rolesTVCnav = [[tabBarController viewControllers] objectAtIndex:1];
RolesTVC *rolesTVC = [[rolesTVCnav viewControllers] objectAtIndex:0];
rolesTVC.managedObjectContext = self.managedObjectContext;
// *** Set up the Materials Views *** (Pass Managed Object Context)//
UINavigationController *materialsTVCnav = [[tabBarController viewControllers] objectAtIndex:2];
MaterialsTVC *materialsTVC = [[materialsTVCnav viewControllers] objectAtIndex:0];
materialsTVC.managedObjectContext = self.managedObjectContext;
// Set delegate for splitViewController
splitViewController.delegate = personDetailTVC;
}
else
{
NSLog(#"I'm an iPhone or iPod Touch");
// The Two Navigation Controllers attached to the Tab Bar (At Tab Bar Indexes 0 and 1)
UINavigationController *personsTVCnav = [[tabBarController viewControllers] objectAtIndex:0];
UINavigationController *rolesTVCnav = [[tabBarController viewControllers] objectAtIndex:1];
UINavigationController *materialsTVCnav = [[tabBarController viewControllers] objectAtIndex:2];
// The Persons Table View Controller (First Nav Controller Index 0)
PersonsTVC *personsTVC = [[personsTVCnav viewControllers] objectAtIndex:0];
personsTVC.managedObjectContext = self.managedObjectContext;
// The Roles Table View Controller (Second Nav Controller Index 0)
RolesTVC *rolesTVC = [[rolesTVCnav viewControllers] objectAtIndex:0];
rolesTVC.managedObjectContext = self.managedObjectContext;
// The Materials Table View Controller (Third Nav Controller Index 0)
MaterialsTVC *materialsTVC = [[materialsTVCnav viewControllers] objectAtIndex:0];
materialsTVC.managedObjectContext = 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] 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:#"Model" 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;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"StaffManager.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options 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:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
i have a example that use the icloud but it is write for ios5, and i don't no what i have to change for ios7:
thats the Code for icloud Support in AppDelegate:
if((__persistentStoreCoordinator != nil)) {
return __persistentStoreCoordinator;
}
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSPersistentStoreCoordinator *psc = __persistentStoreCoordinator;
// Set up iCloud in another thread:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// ** Note: if you adapt this code for your own use, you MUST change this variable:
NSString *iCloudEnabledAppID = #"5KFJ75859U.Tim-Roadley.Staff-Manager";
// ** Note: if you adapt this code for your own use, you should change this variable:
NSString *dataFileName = #"StaffManager.sqlite";
// ** Note: For basic usage you shouldn't need to change anything else
NSString *iCloudDataDirectoryName = #"Data.nosync";
NSString *iCloudLogsDirectoryName = #"Logs";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];
if (iCloud) {
NSLog(#"iCloud is working");
NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];
NSLog(#"iCloudEnabledAppID = %#",iCloudEnabledAppID);
NSLog(#"dataFileName = %#", dataFileName);
NSLog(#"iCloudDataDirectoryName = %#", iCloudDataDirectoryName);
NSLog(#"iCloudLogsDirectoryName = %#", iCloudLogsDirectoryName);
NSLog(#"iCloud = %#", iCloud);
NSLog(#"iCloudLogsPath = %#", iCloudLogsPath);
if([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
NSError *fileSystemError;
[fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&fileSystemError];
if(fileSystemError != nil) {
NSLog(#"Error creating database directory %#", fileSystemError);
}
}
NSString *iCloudData = [[[iCloud path]
stringByAppendingPathComponent:iCloudDataDirectoryName]
stringByAppendingPathComponent:dataFileName];
NSLog(#"iCloudData = %#", iCloudData);
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:iCloudEnabledAppID forKey:NSPersistentStoreUbiquitousContentNameKey];
[options setObject:iCloudLogsPath forKey:NSPersistentStoreUbiquitousContentURLKey];
[psc lock];
[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[NSURL fileURLWithPath:iCloudData]
options:options
error:nil];
[psc unlock];
}
else {
NSLog(#"iCloud is NOT working - using a local store");
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[psc lock];
[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:localStore
options:options
error:nil];
[psc unlock];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:#"SomethingChanged" object:self userInfo:nil];
});
});
return __persistentStoreCoordinator;
i have also this code for ManagedObjectContext :
- (NSManagedObjectContext *)managedObjectContext {
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc performBlockAndWait:^{
[moc setPersistentStoreCoordinator: coordinator];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
}];
__managedObjectContext = moc;
}
return __managedObjectContext;
}
- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
NSLog(#"Merging in changes from iCloud...");
NSManagedObjectContext* moc = [self managedObjectContext];
[moc performBlock:^{
[moc mergeChangesFromContextDidSaveNotification:notification];
NSNotification* refreshNotification = [NSNotification notificationWithName:#"SomethingChanged"
object:self
userInfo:[notification userInfo]];
[[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
}];
}
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.
I am trying to make a journaling application and I am working on deleting entries from Core Data. When I try to delete an object nothing happens, no error message, nothing, and the entry is still there and not deleted. Code:
- (void)deleteButtonPressed:(UIButton *) button {
NSLog(#"Button Pressed");
NSLog(#"%i", button.tag);
UIView *viewToRemove = [self.view viewWithTag:button.tag];
[viewToRemove removeFromSuperview];
UIView *secondViewToRemove = [self.view viewWithTag:button.tag];
[secondViewToRemove removeFromSuperview];
UIView *thirdViewToRemove = [self.view viewWithTag:button.tag];
[thirdViewToRemove removeFromSuperview];
UIView *fourthViewToRemove = [self.view viewWithTag:button.tag];
[fourthViewToRemove removeFromSuperview];
JournalrAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Entrys" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
matches = objects[1];
[context deleteObject:matches];
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
}
Maybe it's because of this line:
matches = objects[1];
Arrays are zero-indexed. So maybe you were looking for the first element (objects[0])?
Do some NSLogs to see if there is actually something to delete.
Also, if you expect some kind of visual update in your views, don't. You must manually update your views to reflect the change in the database.
Our table view controllers use an NSFetchedResultsController to show data from Core Data. We download new data in the background. When an entity is modified in the new data, on iOS 5.1.1 phone, we see that treated as a new row in the table instead of an update. Cannot duplicate on the iOS 5.1 simulator or an iOS 6 device.
The UIApplicationDelegate creates a NSManagedObjectContext with concurrency type NSMainQueueConcurrencyType. Our UITableViewController implements NSFetchedResultsControllerDelegate. In viewWillAppear we go fetch new data. In the method getting data, we create a second NSManagedObjectContext with concurrenty Type NSPrivateQueueConcurrencyType. We do a performBlock on that new context, and do the network call and json parsing. There's a NSFetchRequest to get the previous data, so we can delete the old objects, or modify any existing entities with the same id. After modify the existing entity or creating new ones, we then deleteObject the old entity objects. Then we save this private context. Then on the parent context, do a performBlock to save the changes there.
On iOS5.1, the table is incorrect. If we change on of the objects, instead of being modified, it is added to the table as a new row. If we leave this controller and come back to it, getting new data, it shows the right amount.
AppDelegate.m
- (void)saveContext
{
[self.privateWriterContext performBlock:^{
NSError *error = nil;
[self.privateWriterContext save:&error];
// Handle error...
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:self.privateWriterContext];
}];
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)privateWriterContext
{
if (__privateWriterContext != nil) {
return __privateWriterContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__privateWriterContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[__privateWriterContext setPersistentStoreCoordinator:coordinator];
}
return __privateWriterContext;
}
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[__managedObjectContext setParentContext:self.privateWriterContext];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(saveContext:)
name:NSManagedObjectContextDidSaveNotification
object:__managedObjectContext];
return __managedObjectContext;
}
class that fetches from server
+ (void) fetchFromURL:(NSString *) notificationsUrl withManagedObjectContext (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *importContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
importContext.parentContext = managedObjectContext;
[importContext performBlock: ^{
NSError *error;
NSURLResponse *response;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSData *responseData = [NSData dataWithContentsOfURLUsingCurrentUser:[NSURL URLWithString:notificationsUrl] returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableSet *newKeys = [[NSMutableSet alloc] init];
NSArray *notifications;
if(responseData) {
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSMutableDictionary *previousNotifications = [[NSMutableDictionary alloc] init];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Notification"];
NSArray * oldObjects = [importContext executeFetchRequest:request error:&error];
for (Notification* oldObject in oldObjects) {
[previousNotifications setObject:oldObject forKey:oldObject.notificationId];
}
notifications = [json objectForKey:#"notifications"];
//create/update objects
for(NSDictionary *notificationDictionary in notifications) {
NSString *notificationId = [notificationDictionary objectForKey:#"id"];
Notification *notification = [previousNotifications objectForKey:notificationId];
if(notification) {
[previousNotifications removeObjectForKey:notificationId];
} else {
notification = [NSEntityDescription insertNewObjectForEntityForName:#"Notification" inManagedObjectContext:importContext];
[newKeys addObject:notificationId];
}
notification.notificationId = [notificationDictionary objectForKey:#"id"];
//other properties from the json response
}
for (NSManagedObject * oldObject in [previousNotifications allValues]) {
[importContext deleteObject:oldObject];
}
}
if (![importContext save:&error]) {
NSLog(#"Could not save to main context after update to notifications: %#", [error userInfo]);
}
//persist to store and update fetched result controllers
[importContext.parentContext performBlock:^{
NSError *parentError = nil;
if(![importContext.parentContext save:&parentError]) {
NSLog(#"Could not save to store after update to notifications: %#", [error userInfo]);
}
}];
}
];
}
I suffered the problem recently too.
The problem is because of two contexts in different threads.
On device which is running iOS 5.1, merging them cause it to insert a new record instead of update it. I change the background thread to use main context instead and the problem is gone.
No clue why merging does not work in this particular case.