objective-cbreakpointsassertionscontinuation

Objective C - how to programmatically stop execution for debugging, while allowing continuation?


I have had success getting my debug builds to stop execution when a condition is programmatically specified, using the standard NSAssert(condition_which_should_evaluate_true, @"error message") statement in Objective C, and adding in an "All Exceptions" breakpoint in the Breakpoint Navigator.

Well and good, but most of the time when I'm debugging, I'd also like to continue normal program execution after that point. Often continuing the program after a failed assertion helps to track down the source of the confusion/bug. At least as far as I remember when I was programming on a different platform.

Is there a standard way to do so in Objective C development?


Solution

  • There's a way. It's not an Objective-C thing, it's a Unix thing.

    kill(getpid(), SIGSTOP);
    

    or simply:

    raise(SIGSTOP);
    

    In Swift:

    raise(SIGSTOP)
    

    This will break in the debugger in the __kill or __pthread_kill function. You will need to then go up a few stack frames to look at the frame that called kill or raise. You can use the debugger`s continue command to resume execution.

    Note that if you're not running under the debugger and you execute this, your app will just hang. Take a look at [Technical Q&A QA1631: Detecting the Debugger](http://developer.apple.com/library/mac/#qa/qa1361/_index.html. You can use that information to write a wrapper function or macro that only sends SIGSTOP when running under the debugger. This answer may help.

    Also, the Foundation framework provides a different assert macro for use in regular functions. It's NSCAssert.