NSOperation crash on isCancelled - objective-c

I have implemented a concurrent nsoperation and have ARC enabled. Now my customer is experiencing a crash which I cannot reproduce. He sent me the follow crash log :
Date/Time: 2013-04-24 12:23:34.925 -0400
OS Version: Mac OS X 10.8.3 (12D78)
Report Version: 10
Interval Since Last Report: 30946 sec
Crashes Since Last Report: 1
Per-App Interval Since Last Report: 33196 sec
Per-App Crashes Since Last Report: 1
Anonymous UUID: FB8460EE-5199-C6FB-55DC-F927D7F81A80
Crashed Thread: 15 Dispatch queue: com.apple.root.default-priority
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: EXC_I386_GPFLT
Application Specific Information:
objc_msgSend() selector name: isCancelled
Thread 15 Crashed:: Dispatch queue: com.apple.root.default-priority
0 libobjc.A.dylib 0x00007fff877f1250 objc_msgSend + 16
1 Myapp 0x000000010a608807 0x10a601000 + 30727
2 Myapp 0x000000010a650575 0x10a601000 + 324981
3 com.apple.Foundation 0x00007fff8b66212f -[NSBlockOperation main] + 124
4 com.apple.Foundation 0x00007fff8b638036 -[__NSOperationInternal start] + 684
5 com.apple.Foundation 0x00007fff8b63f861 __block_global_6 + 129
6 libdispatch.dylib 0x00007fff832d0f01 _dispatch_call_block_and_release + 15
7 libdispatch.dylib 0x00007fff832cd0b6 _dispatch_client_callout + 8
8 libdispatch.dylib 0x00007fff832ce1fa _dispatch_worker_thread2 + 304
9 libsystem_c.dylib 0x00007fff87d19d0b _pthread_wqthread + 404
10 libsystem_c.dylib 0x00007fff87d041d1 start_wqthread + 13
My code looks like this:
-(void)start
{
// Always check for cancellation before launching the task.
if ([self isCancelled])
{
// Must move the operation to the finished state if it is canceled.
[self onCancelSyncOperation];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:#"isExecuting"];
[NSThread detachNewThreadSelector:#selector(main) toTarget:self withObject:nil];
executing = YES;
[self didChangeValueForKey:#"isExecuting"];
}
- (void)onCancelSyncOperation
{
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
executing = NO;
finished = YES;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
It seems like the nsoperation is already released? when it tries to check for isCancelled?
Is this possible?

I don't think anyone can tell you why your app crashes by looking at this log. I haven't looked at your code, but you cut your crash-log, so it only shows system modules (lib.dispatch..., com.apple...). Typically the error is in the first occurrence of "com.myname...".
If this kind of crash EXC_BAD_ACCESS (SIGSEGV) appears along with an objc_msgSend(), it probably means you're trying to message to an object (or in other words: call a method of an object) that isn't there anymore. If you call that object, chances are very good that you'll find it, if you call it delayed or on another Thread or from a block, it will be a bit more complicated.
Your best chance to find the cause of this is to inspect your app with Instrument, using the Allocations or Leaks tool with NSZombies enabled (which is the default). You can launch Instruments from within Xcode. Then try to reproduce your crash. If you succeed, you might be able to find the class and location where the crash occurs.
If you don't know what to do with this answer, then check out the WWDC Developer Videos from Apple, there are some that show how to profile your app with Instruments (you'll need a [free] Dev Account to access the videos).
Good luck!

Related

OSX 10.10.3 crashes WebView on dealloc

After updating to 10.10.3 the WebView component started to crash after dealloc
- (void)dealloc {
[self.webView.windowScriptObject setValue:nil forKey:#"CocoaApp"];
[[self.webView mainFrame] stopLoading];
[self.webView setUIDelegate:nil];
[self.webView setEditingDelegate:nil];
[self.webView setFrameLoadDelegate:nil];
[self.webView setPolicyDelegate:nil];
[self.webView removeFromSuperview];
}
The crash happens somewhere deep in WebView
EXC_BAD_ACCESS
1 0x7fff910bae9e WebDocumentLoaderMac::detachFromFrame()
2 0x7fff920288c0 WebCore::FrameLoader::detachFromParent()
3 0x7fff910d0e55 -[WebView(WebPrivate) _close]
4 0x7fff910d0c49 -[WebView dealloc]
5 0x7fff8b1cf89c objc_object::sidetable_release(bool)
6 0x7fff8b1b5e8f (anonymous namespace)::AutoreleasePoolPage::pop(void*)
7 0x7fff912b26f2 _CFAutoreleasePoolPop
8 0x7fff8830e762 -[NSAutoreleasePool drain]
9 0x7fff8e3f0cc1 -[NSApplication run]
10 0x7fff8e36d354 NSApplicationMain
11 0x1000ebb12 main
12 0x7fff8c81e5c9 start
13 0x3
Any ideas? Is this a Apple bug? It started AFTER 10.10.3?
It doesn't crash when NSZombie is enabled!
I noticed you're using your own policy delegate:
[self.webView setPolicyDelegate:nil];
There's a known bug related to policy delegates in WebKit (only very recently fixed):
https://bugs.webkit.org/show_bug.cgi?id=144975
The short version is that you're probably hitting this assertion (which crashes the process with an intentional segfault):
https://github.com/WebKit/webkit/blob/24b1ae89efc10a4e6a6057b429c8e1d8d138a32f/Source/WebCore/loader/DocumentLoader.cpp#L935
because your policy handler (i.e. decidePolicyForMIMEType:request:frame:decisionListener:) is failing to make a policy decision (i.e not use, ignore, or download). The decision hangs around unmade, and when the loader eventually detaches it asserts that there are no pending policy decisions, which fails since the view is still waiting for a decision.
The fix i made, is not to release the webview, but hold a static reference into it (this is far from solving it and i contacted Apple regarding this issue)
#warning HOTFIX
{
//this is because of http://stackoverflow.com/questions/29746074/osx-10-10-3-crashes-webview-on-dealloc
static NSMutableArray * LIVE_FOR_EVER_WEBVIEW;
if (LIVE_FOR_EVER_WEBVIEW == nil) {
LIVE_FOR_EVER_WEBVIEW = [NSMutableArray new];
}
if (self.webView) {
[LIVE_FOR_EVER_WEBVIEW addObject:self.webView];
}
}

iOS app crashes on resuming

(SEE UPDATE AT THE BOTTOM)
Recently I've started getting a weird and rare crash of my iPhone app when it returns from background. The crash log consists of system calls only:
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000138
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x34c715b0 objc_msgSend + 16
1 CoreFoundation 0x368b7034 _CFXNotificationPost + 1424
2 Foundation 0x34379d8c -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
3 UIKit 0x37ddfec2 -[UIApplication _handleApplicationResumeEvent:] + 1290
4 UIKit 0x37c37d5c -[UIApplication handleEvent:withNewEvent:] + 1288
5 UIKit 0x37c376d0 -[UIApplication sendEvent:] + 68
6 UIKit 0x37c3711e _UIApplicationHandleEvent + 6150
7 GraphicsServices 0x36dea5a0 _PurpleEventCallback + 588
8 CoreFoundation 0x3693b680 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 12
9 CoreFoundation 0x3693aee4 __CFRunLoopDoSources0 + 208
10 CoreFoundation 0x36939cb2 __CFRunLoopRun + 642
11 CoreFoundation 0x368aceb8 CFRunLoopRunSpecific + 352
12 CoreFoundation 0x368acd44 CFRunLoopRunInMode + 100
13 GraphicsServices 0x36de92e6 GSEventRunModal + 70
14 UIKit 0x37c8b2fc UIApplicationMain + 1116
15 [MyAppName] 0x00083d60 main (main.m:20)
16 [MyAppName] 0x00080304 start + 36
This might look like a zombie object being called on UIApplicationWillEnterForegroundNotification or UIApplicationDidBecomeActiveNotification (guessing by _handleApplicationResumeEvent in stack trace and the time when it crashes), but:
None of my classes register for UIApplicationDidBecomeActiveNotification, and only a couple of singletons (that stay alive forever) register for UIApplicationWillEnterForegroundNotification;
I've done some experimenting, and it turns out that posting UIApplicationWillEnterForegroundNotification goes from [UIApplication _sendWillEnterForegroundCallbacks:], and it isn't in the crash log.
For me, all this implies a bug in some library I'm using, or a system bug, and the crash occurred once on iOS 5.1.1 (release build), once on iOS 6.0 (release build) and once on iOS 6.0 (debug build). I scanned every library I'm using and have access to the source code for, and they aren't registering for neither UIApplicationWillEnterForegroundNotification nor UIApplicationDidBecomeActiveNotification. The only library I don't have access to is TestFlight, but the crash occurred on both 1.0 and 1.1 versions of TestFlight, and I've been using the former for quite a while now, without such problems.
So, summing up, I have no idea why has this crash come up and what's it coming from. Any ideas?
UPDATE 1
I've investigated the issue a bit deeper, thanks to DarthMike and matt for their help. By using notification center callback and logging stack trace, I've discovered that this exact stack comes up when and only when UIApplicationResumedNotification notification is fired as a part of returning from background. And guess what - it's some "private" notification and it doesn't have a public identifier counterpart. It doesn't have userInfo and its object is UIApplication (as many other notifications that are posted before this). Obviously I don't use it, neither does any library I have source code for. I can't even find any reasonable mentioning of it in the Internet! I also highly doubt that TestFlight is the culprit, because crash happened during debug too, and I don't "take off" TestFlight in debug mode.
Here's the stack trace for receiving UIApplicationResumedNotification. The offsets are all the same but with a constant byte offset (2 or 4, depending on the library - probably because it's a debug stack tracing, not release):
0 [MyAppName] 0x0016f509 NotificationsCallback + 72
1 CoreFoundation 0x3598ce25 __CFNotificationCenterAddObserver_block_invoke_0 + 124
2 CoreFoundation 0x35911037 _CFXNotificationPost + 1426
3 Foundation 0x333d3d91 -[NSNotificationCenter postNotificationName:object:userInfo:] + 72
4 UIKit 0x36e39ec7 -[UIApplication _handleApplicationResumeEvent:] + 1294
5 UIKit 0x36c91d61 -[UIApplication handleEvent:withNewEvent:] + 1292
6 UIKit 0x36c916d5 -[UIApplication sendEvent:] + 72
7 UIKit 0x36c91123 _UIApplicationHandleEvent + 6154
8 GraphicsServices 0x35e445a3 _PurpleEventCallback + 590
9 CoreFoundation 0x35995683 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
10 CoreFoundation 0x35994ee9 __CFRunLoopDoSources0 + 212
11 CoreFoundation 0x35993cb7 __CFRunLoopRun + 646
12 CoreFoundation 0x35906ebd CFRunLoopRunSpecific + 356
13 CoreFoundation 0x35906d49 CFRunLoopRunInMode + 104
14 GraphicsServices 0x35e432eb GSEventRunModal + 74
15 UIKit 0x36ce5301 UIApplicationMain + 1120
16 [MyAppName] 0x000aa603 main + 390
17 [MyAppName] 0x000a41b0 start + 40
NotificationsCallback is an "observer" callback I've added for debug just for now.
Just to prove a point, I've deliberately omitted a removeObserver: call from one of my objects to generate a zombie/exception, and stack trace still included _CFXNotificationPost + 1426 followed by a crash with EXC_BAD_ACCESS in objc_msgSend + 16, just as in my original crash.
So this just means that someone has registered an observer for UIApplicationResumedNotification and haven't removed it before the observer was deallocated. Based on the fact that I never registered for such a notification, I can assume that this crash is not my fault. Still the question remains - whose it is then? I wonder who actually registers for this notification anyway...
UPDATE 2
While I'm still waiting to see if there are any changes with this bug on the new version of my app, I've got another crash on the previous version caused by this. Turns out that whatever registers for UIApplicationResumedNotification, specifies selector _applicationResuming: for it. I doubt that's of any use though.
I had exactly the same stack trace in a crash report from a device running IOS 6.0.1. I managed to reproduce the problem on Simulator through the following pattern:
Put the application in the background
Simulate a memory warning from simulator menu
Bring the application back to the foreground
After a lot of debugging I discovered that the _applicationResuming: message is sent to a UITextField which I am releasing as a reaction to Memory Warning. I tested the same pattern under IOS 5.1 but it didn't cause a crash. For some reason in IOS 6 UITextField registers for ApplicationResumeEvent (maybe not always but after the keyboard has appeared).
My workaround was to remove this object from NSNotificationCenter before releasing it:
[[NSNotificationCenter defaultCenter] removeObserver:self.placeFld];
self.placeFld = nil;
I just ran into this issue and found a solution that did not involve removing notifications. In our case, there was old code that was doing this:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
// other stuff
}
I do not know why we had this, but it is gone now and the crash is gone. It appears that in this case, resigning first responder while searchBarTextDidBeginEditing is being called orphans a notification on the search bar's text edit field, and then we'd crash as soon as the view controller owning this UISearchBar was deallocated and we did the background / foreground dance.
YMMV
Put a breakpoint on -[NSNotificationCenter postNotificationName:object:userInfo:]. It's trying to send a notification to an object that isn't there any more, or something like that. You may be mismanaging your own notifications or your own objects.
Consider switching to ARC if you are not using it already.
Use the static analyzer. It can find potential memory issues.
Could be many things, but I think checking in code who registers for ANY UIApplication notification would be better. You don't really know which notification triggers the error.
Also, is any object retaining/holding strong reference on the AppDelegate? It may cause some weird retain cycle making this crash happen.
I've never seen such a crash by XCode misbehaviour.
EDIT: Pasting all notifications from header file. may be overkill but some could be sent on app resume/from background
UIKIT_EXTERN NSString *const UIApplicationDidEnterBackgroundNotification NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN NSString *const UIApplicationWillEnterForegroundNotification NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN NSString *const UIApplicationDidFinishLaunchingNotification;
UIKIT_EXTERN NSString *const UIApplicationDidBecomeActiveNotification;
UIKIT_EXTERN NSString *const UIApplicationWillResignActiveNotification;
UIKIT_EXTERN NSString *const UIApplicationDidReceiveMemoryWarningNotification;
UIKIT_EXTERN NSString *const UIApplicationWillTerminateNotification;
UIKIT_EXTERN NSString *const UIApplicationSignificantTimeChangeNotification;
UIKIT_EXTERN NSString *const UIApplicationWillChangeStatusBarOrientationNotification; // userInfo contains NSNumber with new orientation
UIKIT_EXTERN NSString *const UIApplicationDidChangeStatusBarOrientationNotification; // userInfo contains NSNumber with old orientation
UIKIT_EXTERN NSString *const UIApplicationStatusBarOrientationUserInfoKey; // userInfo dictionary key for status bar orientation
UIKIT_EXTERN NSString *const UIApplicationWillChangeStatusBarFrameNotification; // userInfo contains NSValue with new frame
UIKIT_EXTERN NSString *const UIApplicationDidChangeStatusBarFrameNotification; // userInfo contains NSValue with old frame
UIKIT_EXTERN NSString *const UIApplicationStatusBarFrameUserInfoKey; // userInfo dictionary key for status bar frame
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsURLKey NS_AVAILABLE_IOS(3_0); // userInfo contains NSURL with launch URL
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsSourceApplicationKey NS_AVAILABLE_IOS(3_0); // userInfo contains NSString with launch app bundle ID
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsRemoteNotificationKey NS_AVAILABLE_IOS(3_0); // userInfo contains NSDictionary with payload
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsLocalNotificationKey NS_AVAILABLE_IOS(4_0); // userInfo contains a UILocalNotification
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsAnnotationKey NS_AVAILABLE_IOS(3_2); // userInfo contains object with annotation property list
UIKIT_EXTERN NSString *const UIApplicationProtectedDataWillBecomeUnavailable NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN NSString *const UIApplicationProtectedDataDidBecomeAvailable NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsLocationKey NS_AVAILABLE_IOS(4_0); // app was launched in response to a CoreLocation event.
UIKIT_EXTERN NSString *const UIApplicationLaunchOptionsNewsstandDownloadsKey NS_AVAILABLE_IOS(5_0); // userInfo contains an NSArray of NKAssetDownlo
A few things I do to clear the deck before debugging something an odd crash.
Build Clean (gets rid of local cached files).
Delete the app from Simulator / Device (sometimes XIBs are cached).
Re launch Xcode (there are some weird bugs when Xcode isn't in sync with the current setup).
Then, try again.

iOS app crash only when not debugging

I am using testflight to test my app, and I have a crash that only occurs when the app is built for ad-hoc and distributed through test flight. The relevant crash report details are:
Date/Time: 2012-06-11 09:00:34.638 +0800
OS Version: iPhone OS 5.1.1 (9B206)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000009
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x34e74f78 objc_msgSend + 16
1 appName 0x0002963e __24-[XYPieChart reloadData]_block_invoke_0168 (XYPieChart.m:321)
2 libdispatch.dylib 0x30295c52 _dispatch_call_block_and_release + 6
3 libdispatch.dylib 0x302a0e8a _dispatch_main_queue_callback_4CF$VARIANT$up + 190
4 CoreFoundation 0x371482a6 __CFRunLoopRun + 1262
5 CoreFoundation 0x370cb49e CFRunLoopRunSpecific + 294
6 CoreFoundation 0x370cb366 CFRunLoopRunInMode + 98
7 GraphicsServices 0x3388a432 GSEventRunModal + 130
8 UIKit 0x30e77cce UIApplicationMain + 1074
9 appName 0x00003b20 main (main.m:14)
10 appName 0x00003ad8 0x1000 + 10968
and the code that is referenced - (XYPieChart.m:321)
[CATransaction begin];
[CATransaction setAnimationDuration:_animationSpeed];
[_pieView setUserInteractionEnabled:NO];
__block NSMutableArray *layersToRemove = nil;
[CATransaction setCompletionBlock:^{
if (layersToRemove) {
[layersToRemove enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (obj)
[obj removeFromSuperlayer];
}];
[layersToRemove removeAllObjects];
}
for(SliceLayer *layer in _pieView.layer.sublayers)
{
[layer setZPosition:kDefaultSliceZOrder];
}
[_pieView setUserInteractionEnabled:YES];
}];
BOOL isOnStart = ([slicelayers count] == 0 && sliceCount);
NSInteger diff = sliceCount - [slicelayers count];
layersToRemove = [NSMutableArray arrayWithArray:slicelayers];
BOOL isOnEnd = ([slicelayers count] && (sliceCount == 0 || sum <= 0));
if(isOnEnd)
{
for(SliceLayer *layer in _pieView.layer.sublayers){
[self updateLabelForLayer:layer value:0];
[layer createArcAnimationForKey:#"startAngle"
fromValue:[NSNumber numberWithDouble:_startPieAngle]
toValue:[NSNumber numberWithDouble:_startPieAngle]
Delegate:self];
[layer createArcAnimationForKey:#"endAngle"
fromValue:[NSNumber numberWithDouble:_startPieAngle]
toValue:[NSNumber numberWithDouble:_startPieAngle]
Delegate:self];
}
[CATransaction commit];
return;
}
I would be able to track down the problem if I could reproduce it when debugging but it only seems to occur when built for ad-hoc. Thanks!
Edit:
Using the simulator, I have tracked down the problem to a EXC_BAD_ACCESS at this line
[layersToRemove enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
I had a similar problem and tried changing the project build settings, but it didn't work for me. Eventually solved my problem by changing the compiler optimization level setting for the release:
In Build Settings, go to the LLVM compiler 4.2 - Code Generation section, look for the Optimization Level option and change the Release setting from Fastest, Smallest [-Os] to None [-O0].
Hope this helps!
Change your Xcode Scheme so that you can Test and Debug a Release build, which uses the same compiler optimizations as your Ad Hoc build. Debugging a Debug build does not.
I ended up working out the problem. In my compiler settings, somehow, ARC wasn't enabled for Ad-Hoc builds resulting in weird behaviour. Before I worked this out, allocating the __block variable worked because in non-ARC environments, __block variables are not retained automatically.
Changed compiler settings so that all builds use ARC and everything was fixed.
In my case it was the "Enable Zombie Objects" setting that prevented the crash in debug mode. Debuggin without this setting made the app also crash in the debugger making it easy to find the culprit.
So I would advice to disable all settings in the "diagnostics" menu and set the optimizations to -Os and make a final test before releasing. Or as hotpaw2 pointed out, build in release mode. But this did not work for me due to issues with the certificate settings.

NSTimer crashing my application

So I have an application which uses an NSTimer. The problem is that when the NSTimer runs, my application will crash with EXC_BAD_ACCESS. I only just started with objective-c so I don't know how to properly debug it. If I thought call the -(void)logIn{} with [self logIn]; the application will work.
My code:
.h
#interface DJ_WAppDelegate : NSObject {
NSTimer *loginTimer;
}
-(void)logIn;
#end
.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self logIn]; // this works
loginTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(logIn) userInfo:nil repeats:YES]; // this fails
}
- (void)logIn {
NSLog(#"Logging in...");
// if I comment out these 2 lines it works with the NSTimer!?... (I've would have more code below)
NSURL *loginConn = [NSURL URLWithString:[NSString stringWithFormat:#"some-website.com"]];
NSInteger loginReturn = [[NSString stringWithContentsOfURL:loginConn encoding:NSASCIIStringEncoding error:nil] intValue];
// when "loginReturn" return "OK" the timer (loginTimer) will be stopped with: [loginTimer invalidate];
// more code would be below... (which works!)
}
So the problem is with the NSURL it think.
Thanks for helping.
EDIT 1:
Here's the crash stack:
EException Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000020
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Application Specific Information:
objc_msgSend() selector name: respondsToSelector:
Thread 0 Crashed: Dispatch queue: com.apple.main-thread
0 libobjc.A.dylib 0x9603bed7 objc_msgSend + 23
1 com.apple.CoreFoundation 0x922ed5f2 _CFStringAppendFormatAndArgumentsAux + 3138
2 com.apple.CoreFoundation 0x922ec979 _CFStringCreateWithFormatAndArgumentsAux + 105
3 com.apple.Foundation 0x9656ebfb -[NSPlaceholderString initWithFormat:locale:arguments:] + 163
4 com.apple.Foundation 0x9656eaae +[NSString stringWithFormat:] + 88
5 com.who.DJ-W 0x00001d56 -[DJ_WAppDelegate logIn] + 116 (DJ_WAppDelegate.m:108)
6 com.apple.Foundation 0x965b08d4 __NSFireTimer + 141
7 com.apple.CoreFoundation 0x922ffadb __CFRunLoopRun + 8059
8 com.apple.CoreFoundation 0x922fd464 CFRunLoopRunSpecific + 452
9 com.apple.CoreFoundation 0x922fd291 CFRunLoopRunInMode + 97
10 com.apple.HIToolbox 0x91646e04 RunCurrentEventLoopInMode + 392
11 com.apple.HIToolbox 0x91646bb9 ReceiveNextEventCommon + 354
12 com.apple.HIToolbox 0x91646a3e BlockUntilNextEventMatchingListInMode + 81
13 com.apple.AppKit 0x9265378d _DPSNextEvent + 847
14 com.apple.AppKit 0x92652fce -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 156
15 com.apple.AppKit 0x92615247 -[NSApplication run] + 821
16 com.apple.AppKit 0x9260d2d9 NSApplicationMain + 574
17 com.who.DJ-W 0x00001c92 start + 54
hope this helps... to find the error
EDIT 2:
With the Zombie Mode on I get this: *** -[CFString respondsToSelector:]: message sent to deallocated instance 0x46d550 I hope this helps.
EDIT 3:
To Ball: Here is the original URL (took away the domain here) /DJW/work.php?user=iBlackbirdi&udid=00000000-0000-1000-80005&key=660e5744e&cmd=slocau&type=get
There are several problems here:
djwLog is a class method so you should call it on the class not the instance
like this: [[self class] djwLog:#"foo bar"]
The URLFromString: method needs the string to contain a valid URL as specified by RFC 1808. Something along the lines of [NSURL URLFromString:#"http://example.com/foo"]
stringWithContentsOfURL:url… is a syncornous method. Unless you have this code running in a separate thread you should not use this. Look at NSURLConnection for a class to asynchronously load data from a URL. Using synchronized calls for this is a bad idea. Always.
intValue returns a signed integer. To get a NSInteger use integerValue. Also if you use stringWithContentsOfURL make sure to check if it's result is nil before calling
integerValue otherwise you might get a result of 0 if the URL call failed or did not return data. A real parser for the API you are calling would be a good idea in any case.
You're calling a class method as if it was an instance method:
[self djwLog:#"Logging in..."];
Since there is no instance-method named djwLog the application crashes. You should either call NSLog directly, make it an instance-method - or preferably make a macro for logging:
#ifdef DEBUG
# define DLog(...) NSLog(#"%s %#", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
#else
# define DLog(...) do { } while (0)
#endif
If you instead of NSLog write DLog - it will only be logging when DEBUG-flag has been defined. In addition to this, it will log the origin of the log message - so you can see which class/method the log entry came from.

How can I stop HIToolbox from catching my exceptions?

This question follows on from my other question on why my app isn't being brought down by exceptions.
The Problem
When an exception is thrown on the main thread via an Action, the app still doesn't crash.
As per Dave's answer to my original question, I've implemented the reportException category on NSApplication and set the uncaught exception handler.
Code
I've got the following in my app delegate, which I've hooked up to a button in my UI to test.
-(IBAction)crashOnMainThread:(id)sender {
[self performSelectorOnMainThread:#selector(crash) withObject:nil waitUntilDone:YES];
}
-(void)crash {
// To test out the exception handling
[NSException raise:NSInternalInconsistencyException format:#"This should crash the app."];
}
When I press the button, my app doesn't crash. When I look at the console log, I see this:
06/09/2010 14:12:25 EHTest1[26384] HIToolbox: ignoring exception 'This should crash the app.' that raised inside Carbon event dispatch
(
0 CoreFoundation 0x00007fff80ab4cc4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x00007fff819560f3 objc_exception_throw + 45
2 CoreFoundation 0x00007fff80ab4ae7 +[NSException raise:format:arguments:] + 103
3 CoreFoundation 0x00007fff80ab4a74 +[NSException raise:format:] + 148
4 EHTest1 0x00000001000010e3 -[EHTest1_AppDelegate crashLapsus] + 63
5 Foundation 0x00007fff88957c25 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 234
6 Foundation 0x00007fff8896ad48 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 143
7 EHTest1 0x0000000100001030 -[EHTest1_AppDelegate crashOnMainThread:] + 60
8 AppKit 0x00007fff85c7e152 -[NSApplication sendAction:to:from:] + 95
9 AppKit 0x00007fff85ca26be -[NSMenuItem _corePerformAction] + 365
** Snip **
It looks like Carbon is catching the exception, which is really annoying.
This suggests that for any action code, you need to immediately run it in a background thread so any exceptions are registered as uncaught. Huh? I've not seen any code that's structured like this.
What I've tried
Crashing the app with a delay so it's not connected to a UI element. It crashes fine.
I've tried installing a custom NSExceptionHandler using this in my app delegate:
-(BOOL)exceptionHandler:(NSExceptionHandler *)sender
shouldHandleException:(NSException *)exception
mask:(unsigned int)aMask {
abort();
return YES;
}
-(void)applicationWillFinishLaunching:(NSNotification *)aNotification {
NSExceptionHandler *handler = [NSExceptionHandler defaultExceptionHandler];
[handler setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
[handler setDelegate:self];
}
the problem here is it crashes on every exception, whether it's caught or not.
If I try and check the mask and don't crash on a caught exception, I'm back to square 1 as it seems that HIToolbox catches the exception in exactly the same way as a try/catch block would.
Questions
How can I stop HIToolbox catching the exceptions so that my app uses the uncaught exception handler and crashes?
Is it OK to be running code that's in the same call stack as an action? Surely this is OK?
If it's not OK, what's the alternative?
This is driving me up the wall, so any help would be much appreciated.
I answered your last question on this subject, and ran into the same problem with Carbon's HIToolbox catching exceptions thrown by IBActions.
First, undo everything I mentioned in my previous answer. It doesn't work with IBActions for some reason. My hunch is that HIToolbox lives lower on the exception-handling-chain, and gets any IBAction/GUI exceptions before NSApplication has the opportunity to. Any custom exception-handling function you can register with NSSetUncaughtExceptionHandler() lives (I believe) at the top of the chain.
You're on the right track with NSExceptionHandling:
Add the ExceptionHandling.framework to your Xcode Project
#import "ExceptionHandlerDelegate.h" into your AppDelegate.m (or a custom Singleton exception class)
Inside AppDelegate.m:
// Very first message sent to class
+ (void)initialize
{
NSExceptionHandler *exceptionHandler = [NSExceptionHandler defaultExceptionHandler];
unsigned int handlingMask = NSLogAndHandleEveryExceptionMask;
[exceptionHandler setExceptionHandlingMask:handlingMask];
[exceptionHandler setDelegate:self];
// ...
}
#pragma mark -
#pragma mark NSExceptionHandler Delegate Methods
// Called 1st: Should NSExceptionHandler log the exception?
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:(NSException *)exception mask:(unsigned int)aMask
{
// ...log NSException if desired...
return NO; // Changes to YES if NSExceptionHandler should handle logging
}
// Called 2nd: Should NSExceptionHandler handle the exception?
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:(NSException *)exception mask:(unsigned int)aMask
{
// ...crash your app here (e.g. [NSApp terminate:self]; )
// ...or handle the NSException and return YES/NO accordingly
return NO; // If app crashed, never gets returned - should crash before that
}
The NSLogAndHandleEveryExceptionMask flag tells NSExceptionHandler to capture every exception it can (for your app only, I believe), regardless of where on the exception chain it exists.
This means that #catch/#try/#finally blocks won't work, because the NSHandleOtherExceptionMask flag tells NSExceptionHandler to capture "everything below it" on the exception-handler chain. You can remove that flag, but then HIToolKit will probably get any IBAction exceptions again, since it appears to be lower on said chain.
Apple's docs have info about the flags: NSExceptionHandler docs
So when an NSException is raised (anywhere in your app AFAIK), and NSLogAndHandleEveryExceptionMask is set, these are called in the delegate in-order:
-exceptionHandler:shouldLogException:mask: is called first.
-exceptionHandler:shouldHandleException:mask: is called second.
Just put your "crash code" inside the second delegate method and you should be OK.
Helpful article: Understanding Exceptions and Handlers in Cocoa
The reason I think you were having trouble getting NSExceptionHandler's delegate to work is because it's NOT compatible with a custom method set with NSSetUncaughtExceptionHandler(), which was part of the answer in my previous question. Per Apple:
The NSExceptionHandler class provides
facilities for monitoring and
debugging exceptional conditions in
Objective-C programs. It works by
installing a special uncaught
exception handler via the
NSSetUncaughtExceptionHandler
function. Consequently, to use the
services of NSExceptionHandler, you
must not install your own custom
uncaught exception handler.
It also probably doesn't work well when you override NSApplication's -reportException: method.
Lastly, there doesn't appear to be a need to use #catch/#try/#finally (also part of my previous answer). Configuring NSExceptionHandler inside +initialize appears to "kick in" immediately, unlike overriding NSApplication's -reportException: method.
You can’t reliably. Throwing exceptions across API boundaries is not supported unless explicitly documented (and I can’t think of any cases that are explicitly documented).