tags:

views:

611

answers:

5

I think I'm missing something pretty basic here. I have a Utilities class that has some functions that are called from a few different classes. I want to be able to include Utilities.h and just say [Utilities doStuff] and have the doStuff function in Utilities.m be executed, what's the easiest way to do this?

+1  A: 

Import the header in the .m file that's using the utilities class, using #import "Utilities.h. After that, you're free to use any of its methods. Keep in mind though, that if you want to call a method on the class (instead of creating an instance of a Utilities object and calling the method on that) you need to declare it as a class method. To do this you use the + sign instead of a minus, for example + (void)doStuff:(NSString *)aString;.

Apple has some pretty good documents explaining Object Oriented programming if the above example is confusing at all.

Marc Charbonneau
A: 

This can be achieved with a static method in your Utilities class:

@interface Utilities

+(int) doStuff;

@end

The + sign makes the method static, as opposed to -, which is an instance method.

Andy White
The Objective-C term is “class method”.
Peter Hosey
+4  A: 

The easiest way is to not make Utilities a class, unless there is some reason why you need to create instances of it. Since by nature your utility functions are a loose collection with no common theme, there's no reason to try to force an object-oriented paradigm on them. (Unlike Java, in C based languages, not everything has to be in a class.) Just define them as traditional C style functions, and call them as such. If you really want to use the bracket notation on something that isn't an object and doesn't belong to anything that should be a class, then you can use the + notation as others have suggested.

I agree with Mr. unknown (google). Functions are part of the language. There's nothing wrong or shameful about using them if that's the functionality you want.
Chuck
+2  A: 

The stuff that you need Utility-classes for in other languages are often in Objective-C better implemented as Categories. That is adding to the classes without creating a subclass.

Instead of having a StringUtitities-class you would create StringUtilities category for the NSString class. This is of course not true in every case but for a lot of Utility-class it is.

It's described in more detail at http://macdevelopertips.com/objective-c/objective-c-categories.html

suraken
A: 
Ben