Accessing Method from other Classes Objective-C Accessing Method from other Classes Objective-C objective-c objective-c

Accessing Method from other Classes Objective-C


Option 1:

@implementation commonClass+ (void)CommonMethod:(id)sender  /* note the + sign */{//So some awesome generic stuff...    }@end@implementation ViewController2- (void)do_something... {    [commonClass CommonMethod];}@end

Option 2:

@implementation commonClass- (void)CommonMethod:(id)sender{//So some awesome generic stuff...    }@end@implementation ViewController2- (void)do_something... {    commonClass *c=[[commonClass alloc] init];    [c CommonMethod];    [c release];}@end

Option 3: use inheritance (see Mr. Totland's description in this thread)

@implementation commonClass- (void)CommonMethod:(id)sender{//So some awesome generic stuff...    }@end/* in your .h file */@interface ViewController2: commonClass@end

naturally you always need to #import commonClass.h in your view controllers..


There are some answers here telling you to create a common "parent" class. However I think that you can do a lot better. Create a category for UIViewController instead. You don't know all of the internals of what is going on with UIViewController so I don't think it is worth creating your own View Controller hierarchy off of. In fact it could be dangerous. I ran into a number of problems when I tried to create a "base" UITableViewController and then create classes that inherit from that. I avoided these problems by using categories instead.

Your #1 priority shouldn't be inheriting things for no good reason, it should be getting an app into the app store that people will want to download.


It sounds to me like the common code doesn't need to be in a class at all. Is there a reason you can't just use a C-style function for what you want to do?

You could put the common code in a class and then make your other two classes subclasses of that one; this method also avoids the code duplication.

Another option might be to write a class method instead of instance methods for this common code. I think most people feel that singletons are best avoided as a design choice.

It would be easier to give a good answer if we knew more about what you were really trying to accomplish.