Question

I am trying to write a library so that it is generic enough that its useful. The problem is that it needs to update properties of other classes, both the property and class should be dynamic.

Now I can do it using public variables no problem, I just pass a pointer to the variable I want to update. However it would also be incredibly useful to set properties of classes as well, since they are used so liberally in objective C.

Now again this isn't a problem as long as the property is an object type, trying to set primitive type properties.

My current code looks something along these lines for properties:

NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:[[myInstance class] instanceMethodSignatureForSelector:mySelector]];
[invoc setTarget:myInstance];
[invoc setSelector:mySelector];
[invoc setArgument:&myObject atIndex:2];
[invoc invoke];

However the setArgument method only allows for pointer types, yet properties are allowed to have any primitive type. Is there any way of dynamically assigning primitive type properties?

Was it helpful?

Solution

KVO should do the conversion for you:

[object setValue:[NSNumber numberWithInt:i] forKey:@"myVar"];

will convert the NSNumber to an int if your myVar is defined as:

int myVar;
...
@propery (nonatomic) int myVar;

OTHER TIPS

"However the setArgument method only allows for pointer types" You're missing something. The argument to setArgument: is not the data you are passing to the method. It is the address of the data (of whatever type) you are passing. Right now your code above takes the address of an object pointer (it is a pointer to a pointer). You can just as easily make it take the address of an integer (it doesn't care). In other words, your same exact code already works regardless of type:

NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:[myInstance methodSignatureForSelector:mySelector]];
[invoc setTarget:myInstance];
[invoc setSelector:mySelector];
int myInt = 42;
[invoc setArgument:&myInt atIndex:2];
[invoc invoke];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top