Search code examples
objective-cdesign-patternsfactory-pattern

Factory Method Pattern in Objective C: NSClassFromString()


I have identified an area in an application I am developing where the factory method pattern seems appropriate. I am reasonably familiar with this pattern in other languages (C#, Java), but I was reading the book "Cocoa Design Patterns" and it contains a chapter on Dynamic Creation, which shows how to use the NSClassFromString() method. Of this function, it says:

This single function effectively reduces the well-known Factory Method pattern to a single line of code in many cases.

I am wondering whether I should use this dynamic creation method instead of a typical factory method pattern? Does the dynamic creation method win over the normal method every time, or are there occasions where one is more suitable than the other?

Right now, I am leaning towards using a regular factory method pattern, but I was wondering what others think?

Regards, Nick


Solution

  • The claim in the book is a little strong, I'd say.

    You should use NSClassFromString in two circumstances:

    • You're reading the class name as a string at runtime. Obviously if you get the class name as a string, you have to convert it to a class object somehow, and NSClassFromString is one way to do that. You should probably be testing the string (or the returned class object) against a whitelist of allowable classes, if you don't trust the source of the string.

    • You're weak-linking a framework and using an SDK/platform that doesn't support the NS_CLASS_AVAILABLE feature. Check out the SDK Compatibility Guide for more information about this.

    In any other circumstance, it's probably better to get the class object using an expression like [MyClass class]. That way, you'll get an error at compile-time if the class doesn't exist (for example because you misspelled the class name).