Core Data database doesn't save - iphone

I'm trying to implement the Paparazzi 2 assignment from the Stanford CS193 course and I'm running into a problem. My one call to save the database is when the app exits (I'm borrowing heavily from Mike Postel's version to check my code):
- (void)applicationWillTerminate:(UIApplication *)application {
if (flickrContext != nil) {
if ([flickrContext hasChanges] == YES) {
NSError *error = nil;
BOOL isSaved = [flickrContext save:&error];
NSLog(#"isSaved? %#", (isSaved ? #"YES" :#"NO") );
// Replace this implementation with code to handle the error appropriately.
if(isSaved == NO){
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
}
Unfortunately, this doesn't seem to be doing the job. I'm getting the occasional EXEC_BAD_ACCESS call that might be related to this, but the database never saves. I've inserted the save into other pieces and it works fine there, just not in this routine. I'm not releasing any of the managed objects in my views, just the managed object context (flickrContext, or whatever I'm calling it in a view).
Any ideas?

Are you sure that applicationWillTerminate: is even being called?
With iOS4 and background process support, the usual application lifecycle is now:
running -> background -> background suspended -> exit
You get an applicationDidEnterBackground: call when transitioning into the background state, but no further notification when the background process suspends or exits.
So, you really need to save state in applicationDidEnterBackground: for iOS4, as well as in applicationWillTerminate: for older versions

flickrContext is your managedObjectContext? I'm betting it is nil or otherwise hosed when you hit this method. You say you are releasing it in a view - surely you should be creating just one, having it owned by the application delegate, and release it only in app delegate's dealloc?
(And when you need to use it -
NSManagedObjectContext* moc = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
)
Regarding your EXEC_BAD_ACCESS - what happens with NSZombieEnabled = YES? What does the static analyzer say?

Good call. I actually solved this one the old fashioned (brute force) way. It turns out that applicationWillTerminate wasn't being called, but it wasn't obvious. The routine to create the database that I had borrowed from the web was explicitly releasing an NSArray that I'm pretty sure was autoreleased. It essentially turned the program into a time bomb. Although I still haven't figured out why it lasted as long as it did and just didn't manifest until I tried to exit.
I'm still learning XCode and CocoaTouch. I know about NSZombieEnabled but I haven't figured out how to use it correctly yet. I'm still in the ham-fisted monkey stage. Thanks for the tips, though. They were helpful.

Related

Prevent NSDocument-based app from reopening documents after a crash

I have a read-only music player app for macOS that uses NSDocument to get all the file-handling logic for free.
The problem that I now have is that every time the app crashes (or is stopped by the debugger) while one or more player windows are open, they automatically get reopened when the app is restarted. I don't want that, since it interferes with debugging and legitimate crashes don't really happen with this app.
Apple's NSDocument documentation contains nothing regarding the reopening of files, so I'm out of luck there. Is there a proper way to do this?
First create a subclass of NSDocumentController and make sure you create an instance of it in - (void)applicationWillFinishLaunching:(NSNotification *)notification so it becomes the sharedDocumentController. (see this question)
Then in you subclass override the restore method:
+ (void)restoreWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler
{
if (_preventDocumentRestoration) { // you need to decide when this var is true
completionHandler(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]);
}
else {
[super restoreWindowWithIdentifier:identifier state:state completionHandler:completionHandler];
}
}

Resolving Conflicts in Core Data with iCloud

I'm writing an app that uses Core Data and is synced with iCloud. To do this, I have a UIManagedDocument that I set up as shown below:
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:[self iCloudStoreURL]];
document.persistentStoreOptions = #{NSPersistentStoreUbiquitousContentNameKey: [document.fileURL lastPathComponent], NSPersistentStoreUbiquitousContentURLKey: [self iCloudCoreDataLogFilesURL], NSMigratePersistentStoresAutomaticallyOption: #YES, NSInferMappingModelAutomaticallyOption : #YES};
self.mydoc = document;
[document release];
[document.managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentContentsChanged:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:document.managedObjectContext.persistentStoreCoordinator];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentStateChanged:) name:UIDocumentStateChangedNotification object:document];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.mydoc.fileURL path]]) {
// does not exist on disk, so create it
[self.mydoc saveToURL:self.mydoc.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self populateTable];//synchronous call. few items are added
[self iCloudIsReady];
}];
} else if (self.mydoc.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self.mydoc openWithCompletionHandler:^(BOOL success) {
[self iCloudIsReady];
}];
} else if (self.mydoc.documentState == UIDocumentStateNormal) {
// already open and ready to use
}
}
My issue with this approach is that I keep getting "Optimistic locking failure" when running the app in two devices. I read in Apple's Core Data documentation that a way to "avoid" this kind of issue was to set up the merge policy to NSMergeByPropertyObjectTrumpMergePolicy, something that I am already doing but for some reason is not working.
One thing I can't find is how to fix this. For example, if this is something that could happen, my app should be at least aware and prepared to handle this behavior. But I have no idea on how to handle this. For example, how do I get the conflicting objects and resolve them? Because every time this failure happens, I start getting UIDocumentStateSavingError when trying to save the document and the only way to stop getting this error is by killing the app and re-launching it.
I finally figured this out (at least, I think I did). Apparently, on iOS6+ (I have no idea about iOS5) UIManagedDocument takes care of all the merging for you. So, the observer below, which was only responsible for calling "mergeChangesFromContextDidSaveNotification:" was in fact merging what was just merged.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentContentsChanged:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:document.managedObjectContext.persistentStoreCoordinator];
...
- (void)documentContentsChanged:(NSNotification *)notification {
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
Calling "mergeChangesFromContextDidSaveNotification:" was the line responsible for triggering the "Optimistic locking failure". I removed it and everything started working as expected. Unfortunately this only lasted a couple of hours. Now I keep getting the "iCloud Timed Out" error, but this one I'm sure it's Apple's fault.
Anyway, after a ton of bugs and three different iCloud + Core Data approaches, I think I will hold on integrating iCloud into my app. It is far too unstable and buggy. I really wish Apple could have fixed this with iOS6, iCloud + Core Data is a very powerful tool, unfortunately, it is not ready yet.
Thanks to everyone who tried to help.

monitoredRegions empty even though startMonitoringForRegion:desiredAccuracy: is called

I am developing a iPhone app running on iOS5, and am unable to set up geofences when I call the startMonitoringForRegion:desiredAccuracy: method on click of a button.
It works fine in the simulator when I print out the regions in monitoredRegions, but when running on an actual iPhone 4, the monitoredRegions is always empty. Expectedly, the didEnterRegion: and didExitRegion: methods are not called as well.
Another puzzling fact is that on BOTH the simulator and the iPhone 4 device, the CLLocationManagerDelegate method didStartMonitoringForRegion: is never called as well.
Would appreciate some help here, thank you!
EDIT:
this is method that I call on click of a button:
-(void) queueGeofence: (CLLocationCoordinate2D)selectedBranch userCoordinate:(CLLocationCoordinate2D)userCoordinate radius: (CLLocationDegrees)radius {
geofence = [[CLRegion alloc] initCircularRegionWithCenter:selectedBranch radius:radius identifier:#"geofence"];
CLLocationAccuracy acc = kCLLocationAccuracyNearestTenMeters;
[locationManager startMonitoringForRegion:geofence desiredAccuracy:acc];
[CLLocationManager regionMonitoringEnabled];
NSLog([CLLocationManager regionMonitoringEnabled] ? #"regionMonitoringEnabled:Yes" : #"regionMonitoringEnabled:No");
NSLog([CLLocationManager regionMonitoringAvailable] ? #"regionMonitoringAvailable:Yes" : #"regionMonitoringAvailable:No");
NSLog(#"LOCATIONMANAGER monitored regions: %#", [locationManager monitoredRegions]});
}
Region monitoring is both enabled and available, but monitoredRegions is still giving me back nothing.
If you look in CLLocationManager.h, the comments in the header for startMonitoringForRegion:desiredAccuracy: state that
If a region with the same identifier is already being monitored for this application, it
will be removed from monitoring. This is done asynchronously and may not be immediately reflected in monitoredRegions.
Therefore, you shouldn't necessarily expect that [locationManager monitoredRegions] would include your newly added region since it is added asynchronously.
Are you implementing the delegate method for locationManager:monitoringDidFailForRegion:withError:? Maybe that's getting called instead of locationManager:didStartMonitoringForRegion:. Also note that a region with the same identifier as an existing region will get removed, so you might be running into some unexpected problems because you're reusing "geofence" as your identifier.
First of all, you should be sure, that your app has a permission to use LocationManager. Check it when you alloc your manager.
[CLLocationManager authorizationStatus];
I had the same trouble when start app and decline a permission. And after deleting and rebuilding app. I had a flag, that user didn't accept it. Turn it on.
If you are just going by your NSLog, it probably isn't going to work. [locationManager monitoredRegions] returns an NSSet of CLRegions. They won't display to your log that way. Try this:
NSSet *setOfRegions = [locationManager monitoredRegions];
for (CLRegion *region in setOfRegions) {
NSLog (#"region info: %#", region);
}

Could not locate an NSManagedObjectModel for entity name - Universal App

I have a strange error in my app, which says:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Book'
I know, there are hundrets of "Could not locate an NSManagedObjectModel for entity name" topis here and on the web, but the strange thing is, it's a universal app and the iphone app always works fine, only the ipad app is crashing on startup.
In the main AppDelegate, there is some code in two methodes and in the iphone / ipad AppDelegate I'm calling this code in applicationdidFinishLaunchingWithOptions like this:
if ([self modelExists] == NO) {
[self buildModel];
}
So it's the same way I call the code, but the ipad version crashes and the iphone version does not.
The only different is that the iPhone version uses a TabBarContoller (set up in IB) and the iPad version uses a single viewController (also set up in IB).
It happens on both, simulator and device.
I have no idea what to do. Hope you can understand what I mean ...
Thx a lot
Sebastian
EDIT:
I found out, when I run the iPhone Version, the code in the main AppDelegate is called as it should be, but when I run the iPad Version NONE code of the main appDelegate is called at all, so there is no managedObject created and that's the reason for the error. But why is no code run in the main AppDelegate ? Thx
EDIT2:
This is the code in my main AppDelegate now:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([self modelExists] == NO) { // Checks if the model is allready filled up or not. (Uses CoreData stuff of course)
// iPhone Version is fine here. iPad Version crashes.
[self buildModel];
}
[self buildInterface]; // Called in the iPhone or iPad AppDelegate to make the window visible etc.
return YES;
}
So didFinishLaunchingWithOptions is called in the iphone and in the ipad version. The iPad version just doesn't run the coredata stuff anyway, whereas the iphone version does run the coredata stuff as it should. Any idea what could be wrong? THX!
Maybe the app delegate is not running any code if it's just not set as an delegate of the application.
Look in your main NIB for the iPad version and make sure the "AppName App Delegate" is set as the delegate of the File's owner of that NIB.
I found my problem. Really strange ...
It was the code of "modelExists"
- (BOOL)modelExists {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"Book" inManagedObjectContext:__managedObjectContext]; //<- Crashed. Had to change it to self.managedObjectContext
request.predicate = nil;
NSError *error = nil;
...
Sebastian
I had this same problem. My app had been working fine for weeks in development, then suddenly it was crashing with this error. Changing managedObjContect to [self managedObjectContext] solved the problem.
I would love to know why....any experts out there? Why would the original code be able to resolve the call to managedObjectContext to the member function's implementation....and suddenly not be able to? There is no other static implementation visible to this code as far as I know.
Thank for posting this, save me many hours of messing around.
In my project, I had a navigation controller and I was getting this error when I tried to segue into a child view control.
The problem was that I needed to pass set the managedObjectContext. This is taken from the CoreDate Master/Detail example.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
[[segue destinationViewController] setDetailItem:object];
// set the managedObjectContext, too, if you need it
[[segue destinationViewController] setManagedObjectContext:self.managedObjectContext];
}
}
Also, double check the segue identifier in Interface Builder matches what you have in this function (showDetail in this example).

Invoking [SKProductsRequest start] hangs on iOS 4.0

Encountering an issue with SKProductsRequest that is specific to iOS 4.0. The problematic code:
- (void)requestProductData
{
NSSet *productIdentifiers = [NSSet setWithObjects:kLimitedDaysUpgradeProductId, kUnlimitedUpgradeProductId, nil];
self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
self.productsRequest.delegate = self;
[self.productsRequest start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSLog(#"didReceiveResponse");
}
When [SKProductsRequest start] is invoked, the productsRequest:didReceiveResponse: delegate method is never invoked; further, the entire app hangs and is completely unresponsive to input. Obviously, this is a huge issue for our iOS 4.0 users as it not only breaks payments but makes the app completely unusable.
Some other things to note: this only happens on iOS 4.0; iOS 4.2, 3.x are fine. Also: if the delegate is not set on the SKProductsRequest (i.e. comment out the line "self.productsRequest.delegate = self;"), the app doesn't hang (but of course in that case we have no way of getting the product info). Also, the problem still reproduces with everything stripped out of the productsRequest:didReceiveResponse: callback (that method never actually gets called). Finally, if the productIdentifiers NSSet object is initialized to an empty set, the hang doesn't occur.
Has anybody else experienced this? Any ideas/thoughts on what could be going on here, and how we might be able to work around this?
have you tried implementing –request:didFailWithError: in your delegate, and seeing if that's getting called?
I had a similar problem to this today. No response to any of the delegate methods after I made a SKProductRequest.
Everything was working fine, I didn't make any changes to the IAP code yet it broke.
Finally found the problem. If you self reject the app, then the product ID's you made become invalid. We resolved it by resubmitting the app and creating new ID's. Everything started to work again after that.