Mixins in Objective-C

I hacked up a quick project called ObjectiveMixin. If you’re not familiar with Ruby’s concept of mixins, read up. The basic idea with mixins is that you can extend your class’s functionality with additional methods (from another class) in runtime.

Check out the github page for more details.

Managing Multiple Singleton Classes in Objective-C

There are already numerous articles describing different approaches to using singletons in Objective-C. All aproaches have their upsides and downsides, and I won’t get into that discussion here. Here’s what I wanted from my singleton implementation:

  1. It has to be in one class, which every class wanting to be a singleton must subclass, and by doing so it would get all the singleton functionality “for free”.
  2. It needs to provide a mechanism to kill all instantiated singletons on demand, with one static function call.

Point number 2 is important in a situation where (for example) you have a certain subsystem in your application that is needed only from time to time. Once you’re done with using the subsystem, you don’t want a bunch of its singletons lying around and taking up memory.

A typical singleton approach in Objective-C is to have a single static variable defined in your implementation file that acts as the actual singleton. This is all fine and dandy if you’re amused with rewriting your singleton code in every class that needs to act as a singleton. Personally, if I see the same piece of code scattered around the project, I get pretty pissed off. (See the subtitle of this blog?) Sure, you could just define all the singleton code as a preprocessor macro, and then use that macro in every class declaration, but in my opinion preprocessor macros are bad, bad practice.

So, you can’t use this approach here, because we want to be able to subclass this Singleton class. When you create an instance of the SingletonA class, the static variable inside the Singleton class points to an instance of SingletonA. If you would then request an instance of the SingletonB class in your code, you would get the reference to SingletonA‘s instance variable, since there’s only one variable holding the instance reference, and it’s defined in the base Singleton class. You can work around this problem by introducing additional subclass code, but remember that this is exactly what we want to avoid.

Here’s what I came up with:

Since we need to keep track of multiple subclass instances, we need to have some kind of a collection that remembers each class’ instance. I’m using an NSDictionary, with Class objects as keys, and actual singleton instances as values. (Remember, self refers to the Class value inside class methods.) You can use [SingletonA destroyInstance] to destroy an instance of SingletonA, because instances are mapped by Class values. You can destroy all instances ever created by simply calling [Singleton destroyAllSingletons].

The upside of this approach is that all you have to do to turn your class into a singleton is to subclass the Singleton class. That’s it.

The downside (obviously) is that you’re spending time on dictionary lookup every time you need to fetch a particular instance. I found this to be a practically non-existent issue if you’re using singletons outside of any heavy loops. For example, you should do:

SingletonA singleton = [SingletonA instance];
for (...) {
    [singleton doSomething];

instead of:

for (...) {
    [[SingletonA instance] doSomething];

That way you’re only fetching from the dictionary once.

Testing Asynchronous Code With GHUnit

If you’ve ever done a single unit test run on iOS, you know that Apple’s out-of-the-box unit testing sucks. It’s done at build time, instead of runtime, so there’s no way of debugging your test code. Also, if an exception is thrown at any point in your test code, the testing framework crashes with no meaningful error message or pointer as to where the exception occurred.

Well, it turns out that a guy named Gabriel created his own unit testing framework called GHUnit and shared it on github. It’s a great framework that lets you run your tests in runtime, like it was meant to be. Breakpoints, debugging, fun! I won’t get into details here, since you can read about it all in the project’s README file. Great work, Gabriel!

So, I was writing some asynchronous network code the other day, and I wanted to write tests to check my REST resource fetching and parsing. When you issue an asynchronous method call (like NSURLConnection‘s start, for example), a new thread is spawned for that method to run on, and the thread from which you called your asynchronous method continues to run without waiting for the asynchronous method to finish.

This is bad because your tests will obviously fail if you rely on the results of the asynchronous call. There has to be a way to tell your test’s thread to wait for the asynchronous method to finish, and then continue executing.

When you run your GHUnit target and tap the “Run” button to start the tests, you have the following threads running:

1. Main thread: this is the application’s main thread where typically all your code is executed, but since this is the GHUnit test target, your code won’t be executing here. GHUnit runs its own code on this thread. (Note: You can make your code run on the main thread if you implement the -(BOOL)shouldRunOnMainThread method and return YES, but then your GUI will be unresponsive while your tests are being run. We won’t be doing that here.)
2. Tests thread: all your test code is executed on this thread. You start your asynchronous method from here.
3. Asynchronous method thread: this is where your asynchronous code will run, whatever it is – a network operation, your custom NSOperation subclass, etc.

(There are actually more threads, as can be seen in the debugger, but these three are the ones we’re interested in.)

We need to create a typical signal/wait scenario, which we can achieve by utilizing the NSCondition class. Apple documentation mentions a boolean predicate that should be checked before running any code protected by the condition object (which is in our case a call to signal or wait):

lock the condition
while (!(boolean_predicate)) {
    wait on condition
do protected work
(optionally, signal or broadcast the condition again or change a predicate value)
unlock the condition

Since we only want to signal our test thread and let it know that the asynchronous thread has finished executing, there’s no need to implement this additional predicate logic. It is necessary in cases where you have multiple threads executing the protected code, and a race condition might occur. In our case, we only have one thread waiting for a condition (your test thread) and one thread signaling the condition (your asynchronous method thread), so a predicate is not needed. Note that this is a special case!

Thus, our logic would be more like:

lock the condition
signal the condition OR wait on condition
unlock the condition


On to the code. Here’s an example GHUnit test header file:

We need two variables in this particular case – a condition object which will be used to block the testing thread, and a boolean which will indicate if our asynchronous method finished successfully.

And here’s the implementation file:

In testAsynchronousMethodCall, we create a MyOperation object (which is a fictive NSOperation subclass that you have to implement) and start running its main method on a separate thread. That would be thread number 3 in the list above.

We assume that MyOperation‘s main method calls one of the delegate methods – myOperationDidFinish or myOperationDidFailWithError: – to indicate success or failure. So we set our boolean value connectionSucceeded to reflect that, and then call signal on the condition object, which signals the blocked code on our test thread (number 2 in the list above) to continue executing.

We then test the boolean with STAssertTrue to check if everything went OK, and we’re done.

That’s it! If you have questions or comments, feel free to holler at me. :)


I’ve recently started a project on Github called UnREST. It’s a simple Cocoa Touch library for accessing RESTful web resources through an intuitive code interface. I’m aiming to add some more functionality over time (I’m using REST a lot at work), so if you have some cool ideas or feel like hacking, go for it.

Currently it only supports GET and POST requests, since that’s what I mostly use it for. More stuff to come.

Core Data BLOB Management with Virtual Properties

Keeping BLOBs (Binary Large OBjects) in your Core Data store is generally a bad idea. If you happen to have a large graph of managed objects in your application, it becomes increasingly difficult to manage memory. Faulting can help to a certain extent, but I’ve found it very difficult to successfully manage memory by faulting unused objects in a case where you need all your BLOBs in a single run.

For example, I was writing some code that would print all the photos (represented by the Photo class) in my managed object graph to a PDF file. I tried to ease up on the memory by faulting every Photo object as soon as it was printed. The trouble was – the faults weren’t fired until the entire PDF-printing code ended. Thus, I had all my Photo objects eating up memory, and as soon as all of them were printed (and assuming the app didn’t crash from the lack of memory), they were turned into faults, all at once. Not good.

So I figured I should only keep a URL reference to a photo in my Photo class, and then load the UIImage objects from disk when I needed them. The UIImage objects would not be tied to Core Data in any way, so I could release them at any time.

The header file is pretty straightforward:

The key to this technique is defining virtual properties, and here we have two of them – image and thumbnail. Virtual properties are a nice way of presenting a usable interface to the users of your class, while hiding the actual complexity behind it. Here, we actually don’t have any UIImage references as part of the Photo interface (thus, “virtual”). Instead, we have two NSStrings that hold paths to our images on disk. Whenever a user tries to get the value of the image (or thumbnail) property, our virtual getter loads the image from disk using the imagePath (or thumbnailPath) property, and returns a UIImage object. Similarly, when a user wants to set the image property, the virtual setter takes the UIImage object it received, saves it to disk, and saves the path to imagePath.

This simple technique allows us to separate image handling from Core Data, since we have complete control over the UIImage objects, while Core Data only handles the getting/setting of imagePath and thumbnailPath properties.

The thumbnail is declared as readonly, since it is created as a side effect of setting an image. In other words, there is no way to explicitly define a thumbnail, it is generated for you every time you call the image setter.

On to the implementation:

The generatePath method generates and returns a unique path for the image file, using the current timestamp. The actual filename doesn’t have to be “pretty” because you never get to see it anyway.

fullImagePath and fullThumbnailPath methods return a full path to the image and the thumbnail, respectively. Every time you deploy your app to the device, the actual path to the app folder changes, since your app is given a unique ID for that deployment (for example, /Applications/932479BB-20CD-4EF1-891A-270BCA026AEC/YourApp.app/). These methods fetch the actual app folder path, append the file name (imagePath or thumbnailPath), and return the resulting full path to the JPEG file.

As I mentioned previously, the setImage: method actually behaves as both the image setter, and the thumbnail setter. Note that for resizing the image I’m using the -resizedImageWithSize: method defined in a custom category on UIImage. This basic technique is described in my previous article.

The getters simply read the image/thumbnail from a file and return an autoreleased UIImage reference.

And that’s it! You can now use your managed objects without worrying about Core Data hogging up your memory with image data. Of course, you are still responsible for any objects that you explicitly retain in your code.

Obviously, this technique is applicable to any type of BLOB, not just images. Have fun!

Resizing UIImage objects

If you need a quick way to resize your UIImage objects project-wide, the best way to do so is to add a new method to the UIImage class by defining a category. Categories are Objective-C’s mechanism for extending a class’ functionality without subclassing it.

So, let’s declare a new category named Resizing on UIImage, and place that category’s definition in a file named UIImage+Resizing.h:

We defined a new method, resizedImageWithSize:, which is now available to all of your UIImage objects – you only need to #import "UIImage+Resizing.h" in every source file where you need this functionality.

On to the implementation:

First, we create a new image context by using UIKit’s UIGraphicsBeginImageContext(CGSize size) function. It creates a new image context with the given size, and sets it as the active context.

Now comes the magical part – [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)] draws the receiver (in this case, self) into the currently active context, using the given size. In this case, we want the entire context filled with our original image, so we draw from (0,0) to (size.width,size.height). UIKit does all the hard work of actually resizing the image. Nice!

Next, we need to get an actual UIImage object from our context, so we call UIKit’s UIGraphicsGetImageFromCurrentImageContext() function, which returns an autoreleased UIImage object. Now all we need to do is to end the image context (to prevent memory leaks) by calling UIGraphicsEndImageContext, and return the resulting UIImage object back to the caller.

The actual usage of this code is dead simple:

// Remember to #import "UIImage+Resizing.h"
UIImage* photo = // ... get a photo from somewhere
UIImage* thumbnail = [photo resizedImageWithSize:CGSizeMake(80,60)];

That’s it!

I actually came up with this code after quite a bit of messing around with resizing using Core Graphics, which is a more low-level approach than using UIKit. The memory usage was way too high, since Core graphics relies on the underlying CGImageRef object for drawing, and UIKit seems to do much of it’s job on the GPU, thus minimizing system memory usage.

One more advantage to using UIKit instead of Core Graphics for resizing is when you need to draw a resized image to a PDF context. The UIImage class remembers the source of your image object, so if you draw an object that was loaded from a JPEG file, the image gets embedded into the PDF as a JPEG image. If you resize using Core Graphics, you typically get a CGImageRef object, which you then use to create a new UIImage object, thus losing the information about the source of the image. The image that gets drawn into the PDF context is not compressed, so your PDF file will be bigger.

Populating The Core Data Store With Predefined Data

In my previous article, I’ve shown you a way to turn your managed objects into a dictionary, and vice-versa. In this article, we’ll use that code to populate the Core Data store with data stored in plain-text files in your project’s bundle. We’ll use JSON for representing our objects, but you can generally use any format/library combination that is capable of converting a file into a dictionary. (For example, an XML/NSXMLParser combo.)

The library I’ll use for this example is the excellent TouchJSON library by jwight and buddies. It’s under an MIT license.

Let’s say you have a bunch of template objects that you need pre-loaded in your database upon application’s first launch. You could use these objects later on to instantiate some other objects. Every template object gets its own .template file, holding a JSON representation of the object. The idea here is that your code walks through all the .template files in your app bundle, and loads each JSON object into your Core Data store. Pretty simple stuff.

So, the assumptions are:

  1. The TouchJSON library is copied into your project tree.
  2. You have the dictionary conversion code from my previous article set up and working.
  3. The .template files are added to your project, and are listed in the “Copy Bundle Resources” build phase of your current target.
  4. Each of the .template files holds a single object from your model, represented in JSON format.

For (boring) example, if you have an Employee object with name and address properties, and a relation to a Department object, which in turn has a name property, your JSON representation for an employee would look like:

    "class": "Employee",
    "name": "John Johnson",
    "address": "",
    "department": {
        "class": "Department",
        "name": "Boring Department"

If you want to do it the other way around, you could define a .template for each department, and fill it with employees:

    "class": "Department",
    "name": "Boring Department",
    "employees": [
            "class": "Employee",
            "name": "John Johnson",
            "address": ""
            "class": "Employee",
            "name": "Jane Jansen",
            "address": "21 Nice Avenue"

Notice the “class” attribute. It is a special attribute that the createManagedObjectFromDictionary:inContext: function uses so that it knows the type of object it is about to instantiate and put into a store. You must specify this attribute, otherwise the code will fail.

One small disclaimer though: this approach doesn’t allow complex relationship graphs (or many-to-many relationships), since there’s no way you can reference the same object twice in JSON. So, for example if you’d like an employee to belong to two departments, and then make another employee belong to the same two departments, you would fail. You should consider a different approach than the one described here, if having many-to-many relationships (or any other form of non-trivial relationships) is a requirement for you.

Once you have all of the above taken care of, the actual code is dead simple:

NSArray* templates = [[NSBundle mainBundle] pathsForResourcesOfType:@"template" inDirectory:nil];

for (NSString* template in templates) {
    NSError *error;
    NSData* jsonData   = [NSData dataWithContentsOfFile:template];
    NSDictionary* dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];

    if (error) {
        // ... (handle the error)


    [ExtendedManagedObject createManagedObjectFromDictionary:dict inContext:context];

Add this to your first-run code, and voila.

Serializing (Archiving/Unarchiving) an NSManagedObject Graph

Since the NSManagedObject class doesn’t conform to the NSCopying protocol, there seems to be no easy way to archive a bunch of interrelated managed objects. Once you archive a part of your object graph, you could use the serialized representation for various purposes – sending it over a network, making backups, etc.

The way I figured this could work is to make my NSManagedObject subclass somehow convert an instance of itself into an NSDictionary instance, which would hold all properties and relationships for that particular object. The NSDictionary class conforms to the NSCopying protocol, so once you have the dictionary, you can do whatever you like with it. Of course, you would also need an inverse mechanism that converts an NSDictionary instance into your NSManagedObject.

In order to make the process as transparent as possible, I figured I should create an NSManagedObject subclass, which would sit right between NSManagedObject and your model classes in the inheritance tree. A perfect solution would be able to convert a given object from/to a dictionary without knowing the actual type of the object being converted.

It turns out this solution is possible, and is pretty straightforward to implement. So, let’s call this class ExtendedManagedObject.

@interface ExtendedManagedObject : NSManagedObject {
    BOOL traversed;

@property (nonatomic, assign) BOOL traversed;

- (NSDictionary*) toDictionary;
- (void) populateFromDictionary:(NSDictionary*)dict;
+ (ExtendedManagedObject*) createManagedObjectFromDictionary:(NSDictionary*)dict


So, the interface is pretty straightforward, we basically have two methods that do all the work for us, toDictionary and populateFromDictionary:. The createManagedObjectFromDictionary:inContext: class method is just a helper for creating new managed objects directly from a dictionary. Let’s see how each of these is implemented.

- (NSDictionary*) toDictionary
    self.traversed = YES;

    NSArray* attributes = [[[self entity] attributesByName] allKeys];
    NSArray* relationships = [[[self entity] relationshipsByName] allKeys];
    NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:
                                 [attributes count] + [relationships count] + 1];

    [dict setObject:[[self class] description] forKey:@"class"];

    for (NSString* attr in attributes) {
        NSObject* value = [self valueForKey:attr];

        if (value != nil) {
            [dict setObject:value forKey:attr];

    for (NSString* relationship in relationships) {
        NSObject* value = [self valueForKey:relationship];

        if ([value isKindOfClass:[NSSet class]]) {
            // To-many relationship

            // The core data set holds a collection of managed objects
            NSSet* relatedObjects = (NSSet*) value;

            // Our set holds a collection of dictionaries
            NSMutableSet* dictSet = [NSMutableSet setWithCapacity:[relatedObjects count]];

            for (ExtendedManagedObject* relatedObject in relatedObjects) {
                if (!relatedObject.traversed) {
                    [dictSet addObject:[relatedObject toDictionary]];

            [dict setObject:dictSet forKey:relationship];
        else if ([value isKindOfClass:[ExtendedManagedObject class]]) {
            // To-one relationship

            ExtendedManagedObject* relatedObject = (ExtendedManagedObject*) value;

            if (!relatedObject.traversed) {
                // Call toDictionary on the referenced object and put the result back into our dictionary.
                [dict setObject:[relatedObject toDictionary] forKey:relationship];

    return dict;

First, this function enumerates all attributes and relationships of the object. It then uses key-value coding methods to fetch attribute values and store them into the dictionary object. It also stores its class string into the dictionary, so that the unpacker method knows which object to instantiate.

The procedure is a bit different for relationships, since they can be “to-one” and “to-many”. For “to-many” relationships, we need to fetch a set of all related objects, convert each of them into a dictionary recursively by calling toDictionary, and then add the newly created dictionary to our object’s own dictionary representation.

For “to-one” relationships the process is simpler – we need to check if the object has already been traversed (to prevent infinite recursion), and if not, we convert it to a dictionary and add it to our object’s dictionary representation.

Note: the traversed variable is a very primitive way to check for recursion, as it will only work if you convert an object to a dictionary once in its lifetime. Every subsequent call to toDictionary would only create a shallow dictionary, containing only attributes of the object, since all of its related objects have traversed set to true. The proper implementation is left as an exercise for the reader. ;)

So, on with the methods for converting a dictionary to a managed object:

- (void) populateFromDictionary:(NSDictionary*)dict
    NSManagedObjectContext* context = [self managedObjectContext];

    for (NSString* key in dict) {
        if ([key isEqualToString:@"class"]) {

        NSObject* value = [dict objectForKey:key];

        if ([value isKindOfClass:[NSDictionary class]]) {
            // This is a to-one relationship
            ExtendedManagedObject* relatedObject =
                [ExtendedManagedObject createManagedObjectFromDictionary:(NSDictionary*)value

            [self setValue:relatedObject forKey:key];
        else if ([value isKindOfClass:[NSSet class]]) {
            // This is a to-many relationship
            NSSet* relatedObjectDictionaries = (NSSet*) value;

            // Get a proxy set that represents the relationship, and add related objects to it.
            // (Note: this is provided by Core Data)
            NSMutableSet* relatedObjects = [self mutableSetValueForKey:key];

            for (NSDictionary* relatedObjectDict in relatedObjectDictionaries) {
                ExtendedManagedObject* relatedObject =
                    [ExtendedManagedObject createManagedObjectFromDictionary:relatedObjectDict
                [relatedObjects addObject:relatedObject];
        else if (value != nil) {
            // This is an attribute
            [self setValue:value forKey:key];

+ (ExtendedManagedObject*) createManagedObjectFromDictionary:(NSDictionary*)dict
    NSString* class = [dict objectForKey:@"class"];
    ExtendedManagedObject* newObject =
        (ExtendedManagedObject*)[NSEntityDescription insertNewObjectForEntityForName:class

    [newObject populateFromDictionary:dict];

    return newObject;

The createManagedObjectFromDictionary:inContext: method first creates an ExtendedManagedObject instance, using the “class” key to extract class information, and inserts it into the managed object context. It then calls populateFromDictionary:, which iterates through all keys in the dictionary and checks the type of object returned – it can be a simple attribute, a to-one relationship, or a to-many relationship.

The trick that does most of the dirty Core Data work is a call to [self mutableSetValueForKey:key]. It returns a proxy set summoned by the Core Data subsystem, which does all the database magic for you when you add objects to it. So when you call addObject: on a proxy set object, you’re actually establishing a relationship between the object being added to the set and the owner of the proxy set. Cool stuff!

So there you go, all you have to do is make each of your model classes a subclass of ExtendedManagedObject instead of NSManagedObject, and you can use toDictionary, populateFromDictionary: and createManagedObjectFromDictionary:inContext: to play around with your managed objects. For example, if you have a Person entity in your model, your header file for that class might look something like this:

@interface Person : NSManagedObject {

@property (nonatomic, retain) NSString* name;


Your Person class needs to be a subclass of ExtendedManagedObject, so you need to import the ExtendedManagedObject.h header file, and change “NSManagedObject” to “ExtendedManagedObject”:

#import "ExtendedManagedObject.h"

@interface Person : ExtendedManagedObject {

@property (nonatomic, retain) NSString* name;


Now that your Person class is a subclass of ExtendedManagedObject, you can convert a Person instance to a dictionary with:

Person* person = ... // fetch a person from the core data store, as usual
NSDictionary* personDict = [person toDictionary];

To do the inverse, you need to call the createManagedObjectFromDictionary:inContext method, but since it’s a class method, you need to invoke it statically:

Person* person = ... // fetch a person from the core data store, as usual
NSDictionary* personDict = [person toDictionary];

NSManagedObjectContext* context = ... // your managed object context reference
Person* anotherPerson = [ExtendedManagedObject createManagedObjectFromDictionary:personDict inContext:context];

The above code would convert person to a dictionary (personDict), and then use that dictionary to create a new Person object in the context and assign it to anotherPerson. If you save the context at this point, your store will contain two identical Person objects.

You can also update an existing managed object using the populateFromDictionary: method:

NSDictionary* personDict = ... // Your updated person dictionary (fetched from a web service, for example)
NSManagedObject* person = ... // Fetch your Person managed object from a context

// Update the person managed object using data from the dicitonary
[person populateFromDictionary:personDict];

You can check out the entire code from this gist on Github.

In my next post, I’ll discuss a simple way to load your SQLite database with predefined data when your application is first launched. Stay tuned.

UPDATE: PCKLsoft has posted an updated version of the above gist, thanks man! It turns ExtendedManagedObject int a category on NSManagedObject (much more elegant) and deals with the traversed flag. See his comments for details.

UPDATE 2: nuthatch has yet another improvement on that gist, check it out. Thanks nuthatch.