Reputation: 1069
I declare a class extension interface adding vars to it. Is it possible to access those vars in a category of that class?
Upvotes: 2
Views: 204
Reputation: 55573
Sure - any variable is accessible through the runtime, even if it isn't visible in the @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
You can also use KVC to get iVars of classes in UIKit or similar, while being easier to use than pure runtime-hacking.
Upvotes: 1