Nov 08

Once I started obtaining data from FatSecret via MPOAuthConnect (see previous posts), I had a large JSON string to deal with. I did a quick Google search for a JSON library for Cocoa. I came across json-framework, which is a very simple library. It attaches a Category to NSString to provide a method called JSONValue. Calling JSONValue returns either NSDictionary or NSArray. Yet, another beauty of the langugage, Categories allow you to extend the functionality of an existing Object at runtime.

Once, I called JSONValue on the JSON string, I was able to obtain all the values needed to display the nutritional information for a particular food, and display a list of foods on a search query. This was particularly easy, and a great library.

Tagged with:
Jul 29

Ok, this is easily my favorite feature of the Objective-C language thus far. That is Categories. Categories allows you to modify an existing class “in place”, without having to subclass. In many cases it doesn’t make sense to extend another class if you only wish to add functionality (but add no properties). Also, creating a Category does not require you to add to the inheritance chain which can be problematic if the class you are extending is not under your control.

For our example, I want to add functionality to NSString (a core foundation class). I’ll add a single Class Method that takes any string and presents it as if I’ve said it.

@interface NSString (MarksString)
+ (NSString *) markifyString:(NSString*)string;
@end

When writing the interface, you use the class you are extending (NSString) and define the category (MarksString). You can then add any additional interface elements here.

The implementation is just as expected:

@implementation NSString (MarkString)

   + (NSString *) markifyString:(NSString *) string {
      return [NSString stringWithFormat:@"Mark says \"%@\"", string];
   }
@end

To use this new category, all you have to do is #import the new category, which will add the functionality to NSString at run time.

NSString * original = @"Life is like a box of chocolate";
 NSLog([NSString markifyString:original]);

Displays:

2009-07-29 17:28:58.726 WhatATool[16449:10b] Mark says "Life is like a box of chocolate"
Tagged with:
preload preload preload