Patrick,
On 24. 9. 2016, at 17:11, Patrick J. Collins <[email protected]>
wrote:
> I am trying to change the behavior of a library by subclassing one of the
> files, but am finding this is not working because I can't access (change) one
> of the internal instance variables. ... Is there a way I can get access to
> the _wut ivar in the base class
Note please that this kind of design is conceptually wrong and extremely
error-prone, as Manoah did point out: *never* do this, unless *very* necessary
and no cleaner way out.
If indeed *extremely* necessary, and if you *really* have no cleaner way out,
you can do that, exploiting ObjC runtime, essentially like this:
===
43 /tmp> <q.m
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo:NSObject
-(void)setFoo:(NSInteger)foo;
-(void)showFoo;
@end
@interface Bar:Foo // could be a category just as well, etc.
-(void)dirtyHackSetFooDirectly:(NSInteger)foo;
@end
int main(int ac,char **av) {
id foo=[Bar new]; // if we used a category, subclass would not be needed
[foo dirtyHackSetFooDirectly:666];
[foo showFoo];
return 0;
}
@implementation Foo {
NSInteger _foo;
}
-(void)setFoo:(NSInteger)foo {
_foo=foo;
NSLog(@"unwanted side-effect");
}
-(void)showFoo {
NSLog(@"foo is %ld",(long)_foo);
}
@end
@implementation Bar
-(void)dirtyHackSetFooDirectly:(NSInteger)foo {
object_setInstanceVariable(self,"_foo",(void*)foo);
}
@end
44 /tmp> cc -Wall -framework Foundation q.m && ./a.out
2016-10-16 17:53:21.363 a.out[57747:707] foo is 666
45 /tmp>
===
All the best,
OC
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/objc-language/archive%40mail-archive.com
This email sent to [email protected]