Objective C 中的动态原始类型属性设置
我正在尝试编写一个库,使其足够通用且有用。 问题是它需要更新其他类的属性,属性和类都应该是动态的。
现在我可以使用公共变量来做到这一点,没有问题,我只需传递一个指向我想要更新的变量的指针。 然而,设置类的属性也非常有用,因为它们在 Objective C 中被广泛使用。
现在,只要属性是对象类型,尝试设置基本类型属性,这又不是问题。
我当前的代码看起来与属性类似:
NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:[[myInstance class] instanceMethodSignatureForSelector:mySelector]];
[invoc setTarget:myInstance];
[invoc setSelector:mySelector];
[invoc setArgument:&myObject atIndex:2];
[invoc invoke];
但是 setArgument 方法仅允许指针类型,但属性允许具有任何原始类型。 有什么方法可以动态分配基本类型属性吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
KVO 应该为您进行转换:
如果您的
myVar
定义为:,则将NSNumber
转换为 int:KVO should do the conversion for you:
will convert the
NSNumber
to an int if yourmyVar
is defined as:“但是 setArgument 方法只允许指针类型”您错过了一些东西。
setArgument:
的参数不是您传递给该方法的数据。 它是您传递的数据(任何类型)的地址。 现在,上面的代码采用对象指针的地址(它是指向指针的指针)。 您可以轻松地使其采用整数的地址(它不在乎)。 换句话说,无论类型如何,相同的代码都已经可以工作:"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: