对于实例上的类别,相当于+ [NSObject load]的含义是什么

时间:2014-01-16 08:30:08

标签: objective-c categories

因为你在类别上可以覆盖静态方法

+ (void)load
{
    // do any setup for the class
}

我想知道如何做同样的pr实例。真的有必要调整init方法吗?

1 个答案:

答案 0 :(得分:0)

不,AFAIK没有办法解决这个问题。而是做这样的事情

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (XXXCategory)
@end

@implementation NSObject (XXXCategory)

- (void)xxx_setup
{
    static void * XXXDidSetupPropertKey;
    NSNumber *didSetupValue = objc_getAssociatedObject(self, XXXDidSetupPropertKey);    BOOL didSetup = [didSetupValue boolValue];
    if(!didSetup)
    {
        objc_setAssociatedObject(self, XXXDidSetupPropertKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        NSLog(@"Setting up category");
    }
}

- (void)xxx_doSomething
{
    [self xxx_setup];
    NSLog(@"do something");
}

- (void)xxx_doSomethingElse
{
    [self xxx_setup];
    NSLog(@"do something else");
}

@end

像这样测试

NSObject *obj = [[NSObject alloc] init];
[obj xxx_doSomething];
[obj xxx_doSomethingElse];

结果是

2014-02-28 10:21:04.024 Untitled 2[27026:507] Setting up category
2014-02-28 10:21:04.025 Untitled 2[27026:507] do something
2014-02-28 10:21:04.026 Untitled 2[27026:507] do something else