Reputation: 36013
I have some methods that are used by several classes. My idea was to put these methods on a general separate file and have this be seen by other classes.
How do I do that in Xcode?
Sorry but I am new to iPhone development.
thanks
Upvotes: 3
Views: 112
Reputation: 27597
There are several ways of achieving this. It depends a little on what these classes are that might need the method you talk about. In other words it depends on the level of integration you need. For example; does that method need to work on data encapsulated in those classes.
One approach would be having a singleton helper-class that implements the specific method.
Another approach is a helper-class with a static method (something that Squeegy is very briefly drafting in his answer).
Another approach would be creating a base-class that contains the specific method and all other classes that need this method simply extend the base-class. Let me draft this for you:
BaseClass.h: @interface BaseClass { }; - someNiftyMethodWith:(NSString *)someCoolParameter; @end BaseClass.m: @implementation BaseClass - someNiftyMethodWith:(id)someCoolParameter { NSLog(@"yoy, that was easy to print %@ into the console", someCoolParamater); } @end ExtendingClass.h @interface ExtendingClass : BaseClass { }; - someMethodThatNeedsHelp; @end ExtendingClass.m @implementation ExtendingClass - someMethodThatNeedsHelp { [self someNiftyMethodWith:@"called by the extending class"]; } @end
And there are even more ways of achieving what you might need when using Objective C. Look out for Categories, Delegates, Protocols.
Last but not least there is the very old-school solution of a plain C-function enrolled within a header-file like this:
Helper.h: void OldSchoolHelperFunction(void) { printf("simple helper function"); };
For using this you would include the header Helper.h in all class implementations that might need it
#import "Helper.h" @implemenation FooBar - someMethodThatNeedsHelp { OldSchoolHelperFunction(); } @end
Upvotes: 1
Reputation: 2686
How much of the code needs to be common between classes? Perhaps creating a base class first, and then inheriting from it for the others would be suitable in this case.
Upvotes: 0
Reputation: 187292
I sometimes have a Utility
class that I define only class methods on for this. Anywhere I need to use one of these random methods I simply #import "Utility.h"
and [Utility doSomeHandyThing]
You would define the method with this declaration:
+(BOOL)doSomeHandyThing;
The +
allows you to call it on the class itself without instantiating it first, ideal for quick access to code that doesn't need to depend on any context.
Upvotes: 2