Possible Duplicate:
How to create global functions in Objective-C
I am curious how it is commonly done to create global utility methods in Objective C that any Class can use.
The simple and only solution I can think of is to simply create a class, i.e. call it GlobalMethods, and just create a bunch of class methods so that they can be used without this class ever getting instantiated.
Is this a wise and valid approach? Regarding the type of methods, they might be anything, for example custom math formulas I use, etc.
There are a few common ways to make some code usable globally. Here are some, with examples from Apple’s public APIs:
Create class methods on a new class. This is what you suggested. Examples:
NSPropertyListSerialization,NSJSONSerialization.Create class methods on some appropriate existing class. Example: UIKit uses a category to add class methods to
NSValue, such asvalueWithCGRect:andvalueWithCGPoint:.Create a singleton that understands some group of related messages. Examples:
[UIApplication sharedApplication],[NSFileManager defaultManager].Create plain old C functions. Examples:
UIImagePNGRepresentation,UIRectFill,NSLog,NSStringFromCGPoint, and a pantload more.If the code operates on some object in particular, add a method the the object’s class using a category. Example:
UIKitaddssizeWithFont:,drawAtPoint:withFont:, and related methods toNSStringusing a category.