Monday, September 03, 2012

Update: MyLog with Block

I wrote a utility class to log messages in Objective-C long time ago. I updated the class with block early this year, which is similar as delegate in C#. The reason I like to use blocks is that I think, it will improve my app performance.

Here is what I did before, taking info as an example:

- (MyLogger*) info:(NSString*)messageFormat, ...;

A message string is passed to info method by using a list of dynamic string parameters. No matter if I enabled info logging level or not, the message string would be built on call.

By using a block, the string is built within a dynamic block of codes. The bock is actually a pointer to a function. The block of codes may not be executed at all if the logging level is not enabled. Therefore, I think this strategy would improve app performance.

typedef NSString* (^MessageBuildBlock_t)();
...
- (MyLogger*) info:(NSString* (^)(void))msgBuildBlock;

The block is defined as a function returning a string. Then the block is used as a parameter for info method.

Reference

0 comments: