Int 或 NSInteger 作为方法参数的对象。 Objective-C
我在传递数字作为方法的参数时遇到了一些麻烦:
- (void)meth2:(int)next_int;
要调用该方法,我需要这个:
int next_int = 1;
[self performSelectorOnMainThread:@selector(meth2:) withObject:next_int waitUntilDone:NO];
//update next_int and call meth2 again
此时,我收到一个“来自整数的指针,没有强制转换”错误,并且与 NSInteger
。 NSNumber
没有用,因为它是不可变的,而且我需要不断更改该值。
知道我该怎么做吗?
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只是尝试调用该方法,则可以使用标准语法:
如果您确实需要使用
performSelectorOnMainThread:
,您可以将数字包装在NSNumber
中的电话。你说你不能这样做,因为你需要更改数字,但你可以直接拉出一个 int 并更改它:但也许你的意思是你想要获取数字的值作为调用 < 的输出代码>meth2。如果这就是你的意思,那么你可以传入一个双指针,这样你就可以接收一个新的对象:
当然,这并不是真正的线程安全,所以如果你正在使用多个线程做事情,我建议使用 < code>@synchronized 关键字用于访问多线程访问的变量,或设置原子属性(即未声明为
非原子
的属性)。另外,冰毒对你不好!哈哈
If you're just trying to call the method, you could use the standard syntax:
If you really need to use the
performSelectorOnMainThread:
you could wrap the number in anNSNumber
for the call. You say you can't do this because you need to change the number, but you can just pull an int out and change that:But maybe you mean that you want to get the value of the number as an output from your call to
meth2
. If that's what you mean, then you could pass in a double pointer so you can receive a new object back:Of course, that's not really thread-safe, so if you're doing stuff with multiple threads, I would advise using the
@synchronized
keyword for access to multi-thread-accessed variables, or setting up atomic properties (i.e. properties not declared asnonatomic
).Also, meth is bad for you!! haha
在传递之前将整数包装在 NSNumber 中:
然后您的 -meth2: 方法可能如下所示:
Wrap the integer in an NSNumber before passing it:
Then your -meth2: method could look something like this:
这有点像黑客,但这在 ARC 下有效:
__bridge 关键字将告诉编译器在 ARC 下忽略引用计数,但它需要一个指针,因此您首先必须将 int 转换为 a C 风格的 void 指针。当您的方法收到消息时,它将将该对象指针视为整数。
注意:如果您可以更改方法以采用 NSNumber 而不是整数,那么这将是“正确的”修复。不幸的是,这并不总是可能的。
It's a bit of a hack, but this works under ARC:
The __bridge keyword will tell the compiler to ignore reference counting under ARC, but it requires a pointer, so you first have to cast the int to a C style void pointer. When your method receives the message it will treat that object pointer as if it's an integer.
Note: If you can change the method to take an NSNumber instead of an integer, then that would be the "proper" fix. Unfortunately that's not always possible.
您不能将
next_int
用作withObject:
,因为它不是对象。将您的呼叫更改为:
编辑:
并将
meth2
更改为需要NSNumber
而不是int
。You can't use
next_int
as thewithObject:
because it's not an Object.Change your call to:
EDIT:
And change
meth2
to expect anNSNumber
instead of anint
.