我声明了一个类扩展接口,为它添加了变量。是否可以访问该类别中的那些变量?
答案 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,同时比纯运行时黑客更容易使用。