我声明了一个向其添加变量的类扩展接口。是否可以访问该类的类别中的这些变量?
问问题
195 次
1 回答
1
当然 - 任何变量都可以通过运行时访问,即使它在@interface
:
一些类.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 或类似中获取类的 iVar,同时比纯运行时黑客更容易使用。
于 2012-09-25T19:36:21.580 回答