Int或NSInteger作为方法参数的对象。 Objective-C的 [英] Int or NSInteger as object for method argument. Objective-C

查看:176
本文介绍了Int或NSInteger作为方法参数的对象。 Objective-C的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在传递一个数字作为方法的参数时遇到了一些麻烦:

I'm having some trouble passing a number as an argument for a method:

- (void)meth2:(int)next_int;

要调用该方法我需要这个:

And to call that method I need this:

int next_int = 1;
[self performSelectorOnMainThread:@selector(meth2:) withObject:next_int waitUntilDone:NO];
//update next_int and call meth2 again

此时,我得到一个指针来自没有强制转换的整数错误,并且与 NSInteger 相同。 NSNumber 没用,因为它是不可变的,我需要不断更改值。
我知道怎么办?

at this point, I get a "pointer from integer without a cast" error and would happen the same with a NSInteger. An NSNumber is not useful because it's immutable and I need to change the value constantly. Any idea how can I do this?

谢谢。

推荐答案

如果您只是尝试调用该方法,则可以使用标准语法:

If you're just trying to call the method, you could use the standard syntax:

[self meth2:next_int];

如果你真的需要使用 performSelectorOnMainThread:您可以将该号码包裹在 NSNumber 中以进行呼叫。你说你不能这样做,因为你需要更改数字,但你可以拉出一个int并改变它:

If you really need to use the performSelectorOnMainThread: you could wrap the number in an NSNumber 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:

[self performSelectorOnMainThread:@selector(meth2:) withObject:[NSNumber numberWithInt:next_int] waitUntilDone:NO];
// ... later ...
- (void)meth2:(NSNumber *)number {
  int myInt = [number intValue];
  // do stuff with myInt
}

但也许你的意思是你想要从你的 meth2 的调用获得该数字的值作为输出。如果这就是你的意思,那么你可以传入一个双指针,这样你就可以收到一个新的对象了:

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:

- (void)meth2:(NSNumber **)number {
  int myInt = [*number intValue];
  // do stuff with myInt
  *number = [NSNumber numberWithInt:myInt];
}
// The caller can now operate like this:
NSNumber *number = [NSNumber numberWithInt:next_int];
[self performSelectorOnMainThread:@selector(meth2:) withObject:&number waitUntilDone:YES];
int returnInt = [*number intValue];

当然,这不是真正的线程安全的,所以如果你正在做多线程的东西,我建议使用 @synchronized 关键字来访问多线程访问的变量,或者设置原子属性(即未声明为 nonatomic <的属性/ code>)。

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 as nonatomic).

此外,甲基对你不好!!哈哈

Also, meth is bad for you!! haha

这篇关于Int或NSInteger作为方法参数的对象。 Objective-C的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆