开发者

Repeat the same code in several classes in Objective-C

I have this two functions in my project, that will be identical across several classes.

I cannot create a common base class, since they inherit from different classes (some are UIViewControllers, some are NSObjects, etc.).

I tried with categories, but again, as I don't have a base class, there isn't a single place where to put them. Neither I want the functions to be available in all UIViewControllers, so creating a category there wouldn't help.

How can I add this code to the classes I want without copy & paste?


Just for the record, I'm implementing dynamic log levels in cocoalumberjack, and the code I need to add is the following:

static int ddLogLevel = LOG_LEVEL开发者_如何学C_WARN;

+ (int)ddLogLevel
{
        return ddLogLevel;
}

+ (void)ddSetLogLevel:(int)logLevel
{
        ddLogLevel = logLevel;
}


A bit messy perhaps, but you could use a #define. Create a header file with the following in it:

//LoggingCode.h

#define LOGGING_CODE static int ddLogLevel = LOG_LEVEL_WARN; \
\
+ (int)ddLogLevel \
{ \
    return ddLogLevel; \
} \
\
+ (void)ddSetLogLevel:(int)logLevel \
{ \
    ddLogLevel = logLevel; \
}

Make sure the header file is included whenever you want to use this code, and just insert LOGGING_CODE where you want it.

#include "LoggingCode.h"

LOGGING_CODE

The C preprocessor will do the rest.


Since you can't inherit from a common class, you could make a static class that you would call from both of your other classes.


Edit:

StaticClass.h

+(int)commonddLogLevel;
+(void)commonddSetLogLevel:(int)logLevel;

Class1.h

+(int)ddLogLevel;
+(void)ddSetLogLevel:(int)logLevel;

Class1.m

+(int)ddLogLevel {
    [StaticClass commonddLogLevel];
}

+(void)ddSetLogLevel:(int)logLevel {
    [StaticClass commonddSetLogLevel:logLevel];
}

Class2.h

+(int)ddLogLevel;
+(void)ddSetLogLevel:(int)logLevel;

Class2.m

+(int)ddLogLevel {
    [StaticClass commonddLogLevel];
}

+(void)ddSetLogLevel:(int)logLevel {
    [StaticClass commonddSetLogLevel:logLevel];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜