nsmanageobjectcontext.save stopped working in iOS7 - nsmanagedobjectcontext

The project I inherited was built and launched in April 2013, and it worked perfectly for ios 5.1, ios 6.0 and ios 6.1.
However i just installed the app to an iphone that has ios7.0 and it didn't work. I looked at the code and I see that the app downloads some JSON data from the web, and then when it tries to run the following 3 lines of code, "nothing happens" after the 2nd line.
NSError error = nil;
BOOL isSuccessful =[self.tempMoc save:&error]; // where tempMoc is a NSManagedObjectContext
NSLog(#"errrrrrr ----- %# --- errrrrrr", error);
When I say nothing happens, I mean that the code execution stops on the 2nd line, and no code after that line gets fired. I tried putting a breakpoint on the second line, then stepping into the function, but nothing happens...xcode doesn't show me anything new afterwards. The app in my simulator also hangs.
I tried changing the deployment target of my project from ios6 to ios7. Again, this yielded no effects.
What should I do next?
ADDITIONAL NOTES
I've been reading other stack overflow answers and some people say the a hanging [NSManagedObjectContext save] might be a threading issue. I'm not sure how to confirm if my issue is a threading issue. I know that there's only ONE place that calls the [NSManagedObjectContext save], and that's the one place where things are hanging. I tried putting a
[self.tempMoc.persistentStoreCoordinator lock];
right after instantiating self.tempMoc, but that had no effect.

I figured out the issue.
It was indeed multiple threads manipulating the NSManagedObjectContext that caused hte save function to hang.
My solution was to rewrite the code to get rid of all the extra threads. I was left with only the main thread and this fixed the issue.

Related

Why is my AUv3 randomly disappearing with "viewServiceDidTerminateWithError"?

I’ve encountered a strange problem during iOS AUv3 Instrument development which I’m having trouble finding information on. I’ve spent a couple weeks now attempting to debug this, and I was wondering if anyone else has encountered it. It feels more like an "OS killed the app" than a crash, so I use the term crash loosely. Here are the symptoms:
It doesn't seem to ever happen on initial instantiation; it's when a project is reloaded. But, you can comment out setFullState and it'll still occur.
The “crash” is inconsistent. Like a lot of slippery bugs, it’ll start happening consistently and then it’ll stop happening completely.
When it does happen, it initially appears to load fine: the view loads and looks correct, and it produces audio. But, after a couple seconds, the plugin view disappears and it stops producing audio. I see this in the console log:
viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}
You don’t have to generate any MIDI events to crash it. It would crash even after I commented out the processing block.
If anyone has any ideas, including how to get some useful debugging info out of this situation, let me know!
I tried to look at crash logs, but there are no crash logs generated
didReceiveMemoryWarning is not tripped. In fact, I did an experiment where I allocated 100 megs and memset’d it on startup, and it didn’t crash it.
I tried attaching a debugger, but it goes from “no debug session” to “waiting to attach” after it crashes-- at no point does it actually attach. It will attach if I then reload the plugin, but then it won’t crash. The Zombies and Leaks tools didn't reveal anything, nor did the memory sanitizers.
Using a Storyboard instead of a XIB didn't change the behavior (not sure why it would, but it was one of the last few differences between this and Apple's example).
I created a very tiny example project which exhibits the problem (unfortunately, I cannot post any code which shows the problem because I cannot find where exactly the problem code is-- maybe it's even a project setting?). It has a minimal GUI, no setFullState, and generates white noise:
https://drive.google.com/open?id=1dw3xTHn3qY411eXLaIb_9_S5PAtrr5Nk
Expected: It doesn't crash or disappear randomly
Actual results: After reloading a project file which uses this AUv3, the plugin will disappear after a few seconds. It initially produces audio normally and the GUI looks OK, but then vanishes.

Why am I getting NSFastEnumerationMutationHandler in code that doesn't modify source array/set?

In my crash logs for my latest app version, I got an NSFastEnumerationMutationHandler followed by a crash referencing HKAnchoredObjectQuery initWithType for my code, but I am not intentionally mutating the NSMutableSet sources over which I am fast enumerating.
Here's my code:
for(HKSource* source in sources){
NSPredicate *predicate = [HKQuery predicateForObjectsFromSources:[NSSet setWithObject:source]];
HKAnchoredObjectQuery *newQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType predicate:predicate anchor:anchor limit:HKObjectQueryNoLimit completionHandler:^(HKAnchoredObjectQuery *query, NSArray *results, NSUInteger newAnchor, NSError *error) {
completion(results);
}];
[healthStore executeQuery:newQuery];
}
Any suggestions as to why I am triggering NSFastEnumerationMutationHandler? I am not explicitly touching sources nor have I made a copy of it...is there a way HealthKit could be modifying the source? Even if it were, I would think that modifying source shouldn't trigger this as I am not directly touching sources. Any trouble-shooting advice or error-spotting would be much appreciated.
Here's the exact text from the crash log:
Latest Exception Backtrace:
1. libobjc.A.dylib objc_exception_throw
2. CoreFoundation _NSFastEumerationMutationHandler
3. App name 0x1000d8000
4. App name 0x1000d8000
5. App name 0x1000d8000
6. HealthKit _79-[HKAnchoredObjectQuery initWithType:predicate:anchor:limit:completionHandler:]_block_invoke <---this must be referring to my code above, as it's the only call to initWithType inside a fast enumeration
7. HealthKit _81-[HKAnchoredObjectQuery deliverSampleObjects:deletedObjects:withAnchor:forQuery:]_block_invoke_2 <-- this is an internal HealthKit call. deliverSampleObjects is not a publicly listed method of the interface.
I have not had a crash in the sim or on my phone, so this is the only info I have to go on.
Some code that gets called by the block named completion() in your code snippet is iterating over another collection and is doing so while that array is being modified. Keep in mind that the completionHandler of HKAnchoredObjectQuery runs on a background thread, so your code may be performing unsafe concurrent operations on objects when completionHandler gets called.
It looks like this happens in a block somewhere in a method named
[HKAnchoredObjectQuery initWithType:predicate:anchor:limit:completionHandler:]
So my guess is that the block in question is the completion handler, and the completion handler gets called asynchronously - while someone else is iterating through the same array and maybe modifying it.
Unfortunately this error doesn't show who is causing the trouble, only who is finding the trouble. I'd set a breakpoint on your own callback, check if it is called from a fast enumeration, and try to figure out who else might be modifying the data. Good luck.

10.9 CoreBluetooth RetrivePeriperals

Im developing an app on OSX that uses CoreBluetooth. I have encountered a problem on OSX Mavericks that i cant seem to get around. (All of this works perfectly on OSX 10.8).
First lets go through the flow of the application
This flow is fairly established and has been used used successfully in iOS apps and works on 10.8. So on Mavericks, the first run completes successfully. It scans, finds and connects to the device correctly. It also saves out the UUID of the device to a .plist file along with other properties.
Upon relaunch of the app, it attempts to go down the left hand column of the flow which is where the problems seem to occur.
So the first issue i noticed was that my call to self.central retrievePeripherals: never calls my delegate callback of -(void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals
. It simply never gets the callback on Mavericks.
My next thought was "oh they have a new API for fetching peripherals on Mavericks and the old one is deprecated, lets try that". So i added in my calls to NSArray *identifiers = [self.central retrievePeripheralsWithIdentifiers:#[uuid]]; and i get caught in a sempahore wait trap. Upon closer debugging of what was going on it turned out that sometimes my CBCentralManager gets into a state of CBCentralManagerStateUnknown and never updates the state to a newer one.
The next thing i tried was to fire up Activity Monitor and kill the blued process. Finally, my delegate callback for -(void)centralManagerDidUpdateState:(CBCentralManager *)central was called with the correct CBCentralManagerStatePoweredOn so i performed retrievePeripheralsWithIdentifiers again and received an empty array.
So all of these problems seem to be linked to blued in some way. Does anyone have more insight into this process to elude as to what is going on?
My main question is. Why does this work the first time through the app but not the second? Upon quitting the app after the initial scan and connection it seems i can no longer use the system bluetooth for anything without resetting blued (which even then doesn't retrieve peripherals). Is there some sort of shutdown sequence i need to do on the CBCentralManager to keep blued from going AWOL?
Any advice would be greatly apprecciated!
While this is obviously a very old thread, I stumbled upon the same issue today and decided to post a fix for posterity.
I was trying to hack together a simple app based on the HeartRateMonitor example provided by Apple. Unfortunately, it does not work on 10.9 if autoConnect is set to TRUE, what's worse, it brings blued down on its knees.
In 10.9, a call to the (deprecated) retrievePeripherals freezes blued without a chance to restore. CBCentralManager goes into CBCentralManagerStateUnknown, Bluetooth cannot be turned on/off using OS functions etc. The only solution that I found is to killall -9 blued.
However, the synchronous retrievePeripheralsWithIdentifiers worked well for me (on 10.9.4). Here's the relevant excerpt from the modified HeartRateMonitor code:
/* Retreive already known devices */
if(autoConnect)
{
NSArray *peripherals = [manager retrievePeripheralsWithIdentifiers:[NSArray arrayWithObject:(id)aPeripheral.identifier]];
NSLog(#"Retrieved peripheral: %lu - %#", [peripherals count], peripherals);
[self stopScan];
/* If there are any known devices, automatically connect to it.*/
if([peripherals count] >=1)
{
[indicatorButton setHidden:FALSE];
[progressIndicator setHidden:FALSE];
[progressIndicator startAnimation:self];
peripheral = [peripherals objectAtIndex:0];
[peripheral retain];
[connectButton setTitle:#"Cancel"];
[manager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
}
}

App crash - "DiskImageCache: Could not resolve the absolute path of the old directory."

I am working on an app, where I display the data entered by user in a PDF file. PDF File is also created dynamically.
All this is fine.
I have implemented QuickLook framework to display the pdf file. When I call the QL framework, PDF file id displayed quite fine but when come back to the calling screen, my app crashes without any crash log or memory warnings.
I am calling QL with below code:
[[self navigationController] presentModalViewController:qlPreviewer animated:YES];
logs created are
DiskImageCache: Could not resolve the absolute path of the old directory.
[Switching to process 3070 thread 0x17603]
[Switching to process 3070 thread 0x15503]
This is quite interesting.....
When I run the same program in Instruments to check for leaks and Memory Management, i can only find leaks when PDF document is scrolled and all the pages are viewed.
However, interestingly there is no app crash that I can see.
Also, I did try with ZombieEnabled = YES and without it but no app crash with Instruments.
I am quite clueless on how to interpret this and have been trying different things to solve this. Also, I have tried UIWebView but the result is the same.
I was again trying something to check out the issue and found something interesting.
When i execute the code directly from X-Code - i get the crash in as explained above.
In other instance, if I execute the app by clicking on the app in the sim... no crash
I am yet to check this on device. Can someone confirm the crash on the device?
Also, Google does not have answer to this question.
Thanks in advance for your answers.
Can anyone shed some light on this?
I'm having the exact same issue.
As a workaround, you can disable or remove your 'All Exceptions' breakpoint. This might make debugging a little more difficult, but it's not as bad as having to relaunch the application all the time.
This is the breakpoint causing the issue. I had set it so long ago that I'd forgotten it was there
Deleting application from device helped me to solve this problem.
Maybe also at first you should try "Product > Clean" to ensure that all resources will be copied to your device.
I was able to fix mine with this code:
FirstViewController.h
NSURLRequest* reqObj;
#property(nonatomic, retain) NSURLRequest* reqObj;
FirstViewController.m
reqObj = [NSURLRequest requestWithUrl:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:reqObj delegate:self];
then instead of loading it on my view after this line i waited for the connectionDidFinishLoading then load it to my view
Interesting: This has just started with my app too. No errors when checking for leaks but running the app in the sim actually is causing a Breakpoint, not a crash. I can hit the continue and the app keeps running, no problem.
My issue also is relating to a PDF, but I'm just using a web view to display a PDF from the app bundle. I've checked everything in the dealloc, it's all good, this may be a iOS 5.1 bug. I will update as I learn more.
#JimP, It isn't an iOS 5.1 bug. It has just started happening to my app as well, on iOS5.0. It seems to only affect pdfs of more than one page length, and seems to trigger most commonly on scrolling past the end of the document (although sometimes earlier also). It also seems to happen more often on a second load.
This could happen when you delete the object reference in code but having its reference in xib. Delete the outlet that you no longer need.
Just ran into this problem of loading a pdf file in an App I am converting to iOS 8. This App has been running fine since the first iPhone. I just removed the All Exceptions breakpoint to work around it.
I don't know if it's the same problem but I had an issue where switching from a PDF view to another more than three times via the tab bar controller caused a crash.
Turned out that embedding the views I was switching to within Navigation controllers put a stop to the crashing.

Why does this Objective C call appear to hang?

A friend of mine discovered some strange behaviour with NSDictionary, and I'm curious as to why it happens. Consider the following code:
NSDictionary *dict = [[NSDictionary alloc] init];
// Oops, we can't mutate an NSDictionary
[dict setObject:[[NSNull alloc] init] forKey:#"test"];
NSLog(#"Set");
The code produces a warning upon compilation that "'NSDictionary' may not respond to 'setObject:forKey:'". That's all well and good, and if you run it anyway, you'll get this output in the console:
-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object
Again, exactly what you'd expect to happen. However, at this point the app does not crash or terminate due to an uncaught exception. The setObject:forKey: method simply never returns, and the app appears to hang; the following NSLog is never executed. If you try to step over or into the method using GDB, debugging just seems to end, but without any explicit error message. The app continues to run, but the debugger provides no clue as to where in the code the execution is "stuck."
What's going on here? What is the app actually doing in this case, and why doesn't it crash with an NSInternalInconsistencyException or something of the like?
Edit: For those who have asked, I'm running XCode 4.1 on OS X Lion (10.7.2), building with "Apple LLVM compiler 2.1." I'm using all of the default settings you get with a new Cocoa project in XCode 4. I experience the same non-crashing behaviour regardless of whether I debug the program or just "Run" it. Changing from Debug building to Release building makes no difference. I can even locate the .app file manually in Finder and double click on it to execute it outside of XCode, and it still does not crash.
Exceptions do not crash AppKit programs. NSApplication installs a default exception handler that catches exceptions that your code doesn't. Then you just go back into the runloop as normal.
Lots of apps exhibit this behaviour. It's a common cause of inexplicable blank views/windows. If an exception happens before a view manages to finish drawing, the view will be blank, but the app won't crash. Exceptions only cause a crash if you deliberately change the default exception handler to crash.