views:

69

answers:

2

I want to use some NSAssert stuff and other things to enable better debugging in my app. NSAssert wants a string which it prints if the assertion fails. Nice, but useless unless you type a whole bunch of information in that string, which can become a big mess when done all over the place.

So I want to make a macro that will do the NSAssert call with an string equipped full of useful information like the class name, the method name and other stuff. But more important, I want to provide a custom comment as well. Imagine a macro like this:

USEFUL_ASSERT(foo != nil, @"that wasn't good, really")

for a lot of reasons I can't use a function or method call here, because context would be lost and I could not find out which class caused that problem, which method caused that problem. That can only be done inside that method itself, so I would have to pass a lot of parameters for this information like [self class] and _cmd, but I don't want all this stuff scattered everywhere. The shorter the code to insert, the better to maintain.

Any idea?

+1  A: 
#define USEFUL_ASSERT(condition, comment) /*whatever*/
Chuck
Nice, that looks like if I could just use condition, comment in the definition of the macro? gonna try that! perfect.
HelloMoon
Just remember that this is textual replacement, not variable binding, so for example, if you write `USEFUL_ASSERT(++x == 0, @"It's zero")`, that means `x` will be incremented for each occurrence of `condition` in the macro body.
Chuck
So, for example, if the macro body is `NSLog(@"%u is true? %@", (condition), (condition) ? @"YES" : @"NO")`, this expands to `NSLog(@"%u is true? %@", (condition), (condition) ? @"YES" : @"NO")`. Notice that there are two `++x` expressions here, so `x` gets incremented twice.
Peter Hosey
Makes a lot of sense. Gracias!
HelloMoon
+2  A: 

Take a look at the macro docs.

Ken
good to know there's another FM for that. thanks.
HelloMoon