简体   繁体   English

iOS上线程功能的参数

[英]The parameter of thread function on iOS

I was testing with a thread function. 我正在使用线程功能进行测试。 But the program always feedback an error. 但是程序总是反馈错误。 I guess that the error probably have something to do with the argument of the thread function, but i've no idea how to fix it. 我猜该错误可能与线程函数的参数有关,但我不知道如何解决。 Thx in advance! 提前谢谢! The code is like: 代码如下:

-(void) doSomething:(id)p
{
   if((int)p == 100)
      NSLog(@"100");
   else
      NSLog(@"101");
}

int a = 100;
[self performSelectorInBackground:@selector(doSomething:) withObject:a];

Please read the docs for performSelectorInBackground:withObject: . 请阅读有关performSelectorInBackground:withObject:的文档。 a isn't an object, it's a primitive type. a不是一个对象,它是一个原始类型。

You need to wrap the value in an NSNumber . 您需要将值包装在NSNumber

-(void) doSomething:(NSNumber *)p
{
   if([p intValue] == 100)
      NSLog(@"100");
   else
      NSLog(@"101");
}

int a = 100;
[self performSelectorInBackground:@selector(doSomething:) withObject:@(a)];

Or you can use GCD: 或者您可以使用GCD:

-(void) doSomething:(int)p
{
   if(p == 100)
      NSLog(@"100");
   else
      NSLog(@"101");
}

int a = 100;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self doSomething:a];
});

you should do something like 你应该做类似的事情

[self performSelectorInBackground:@selector(doSomething:) withObject:[NSNumber numberWithInt:a]];

as withObject takes only object and int is primitive datatype. 因为withObject仅接受对象,而int是原始数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM