开发者

iPhone - general methods on a separate file

开发者 https://www.devze.com 2022-12-21 13:05 出处:网络
I have some methods that ar开发者_JAVA技巧e used by several classes. My idea was to put these methods on a general separate file and have this be seen by other classes.

I have some methods that ar开发者_JAVA技巧e 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


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.


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


Just make a custom class that has those methods. This should help you out.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消