在类类别中使用ObjC类扩展的变量

时间:2012-09-25 19:15:04

标签: objective-c categories

我声明了一个类扩展接口,为它添加了变量。是否可以访问该类别中的那些变量?

1 个答案:

答案 0 :(得分:1)

当然 - 任何变量都可以通过运行时访问,即使它在@interface中不可见:

<强> SomeClass.h

@interface SomeClass : NSObject {
    int integerIvar;
}

// methods

@end

<强> SomeClass.m

@interface SomeClass() {
   id idVar;
}

@end

@implementation SomeClass

// methods

@end

<强> SomeClass的+ Category.m

@implementation SomeClass(Category)

-(void) doSomething {
    // notice that we use KVC here, instead of trying to get the ivar ourselves. 
    // This has the advantage of auto-boxing the result, at the cost of some performance.
    // If you'd like to be able to use regex for the query, you should check out this answer:
    // http://stackoverflow.com/a/12047015/427309  
    static NSString *varName = @"idVar"; // change this to the name of the variable you need

    id theIvar = [self valueForKey:varName]; 

    // if you want to set the ivar, then do this:
    [self setValue:theIvar forKey:varName];
}

@end

您还可以使用KVC在UIKit或类似版本中获取类的iVars,同时比纯运行时黑客更容易使用。