Macro Goodness

If you read books on programming they all tell you to write documented code. But even better is to write compact code. Code that is so compact, it can even document itself. Objective-C is already pretty self documenting but some common conventions require you to write the same kind of code ever and ever again, just to follow these conventions. Macros have been ever very helpful in these cases. Following some examples. You can imagine how many macros like this I use in my code.

Objective C 2.0 will make the whole retain release cycle go away but I am still sticked to Tiger.


+ (void)setSomeReference:(NSObject *)object
{
    
BEReferenceWithRetain(_myStrongReferenceobject);
}


Uses this macro. I have others for BEReferenceWithCopy, BERelease and more.


#define BEReferenceWithRetain(ab) \
{ \
    
id bb = b; \
    
if (a != bb) \
    { \
        
if (bb != nil) \
            [
bb retain]; \
        [
a release]; \
        
a = bb; \
    } \
}


Another common task is adding elements to a result set or array. If nothing should be added the method might return nil, but otherwise the resultArray. So this code is a very common task:


NSMutableArray *resultArray = nil;

while (someLoop)
{
    
if (shouldNotAdd)
        
continue;

    
BEAddObjectToMutableArray(resultArraynewItem);
}


It uses this macro


#define BEAddObjectToMutableArray(arrayitem) \
{ \
    
if (item) { \
        
if (array == NULL) {\
            
array = [NSMutableArray arrayWithObject:item]; \
        } 
else {\
            [
array addObject:item]; \
        }\
    }\
}