简体   繁体   English

使用xcode中的线程调用函数

[英]call a function using thread in xcode

i have created a thread in xcode and i have given the function name to be called from that thread. 我在xcode中创建了一个线程,并给了要从该线程调用的函数名称。 but my problem is that the function name which is given to call is not being called(came to know when put a breakpoint in that function) 但我的问题是给调用的函数名称没有被调用(知道何时在该函数中放置断点)

code: 码:

 NSThread* myThread; 
 [myThread start]; 
 [self performSelector:@selector(func1:) onThread:myThread withObject:nil waitUntilDone:false]

and later i tried this one also: 后来我也尝试了这个:

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(func1:)object:nil];
[myThread start]; 

above func1 is the name of the function to be called. func1上方是要调用的函数的名称。

so can any one please tell me how to create the thread and call func1 from there.... 所以任何人都可以告诉我如何创建线程并从那里调用func1。

In your first code sample it doesn't look like you are actually creating a new thread. 在您的第一个代码示例中,您实际上并没有在创建新线程。 You create an empty myThread variable and then call start on it but this will just result in start being sent to nil . 您创建一个空的myThread变量,然后对其调用start ,但这只会导致将start发送给nil The empty thread variable is then sent to the performSelector:onThread:withObject:waitUntilDone: method which will presumably do nothing. 然后,将空线程变量发送到performSelector:onThread:withObject:waitUntilDone:方法,该方法可能什么也不做。

You will need to properly create a thread before you can actually run something on it using performSelector:onThread:withObject:waitUntilDone: . 您需要正确创建一个线程,然后才能使用performSelector:onThread:withObject:waitUntilDone:在线程上实际运行某些东西。

Alternatively, it would be much easier, assuming you don't care which background thread the method runs on, to simply use performSelectorInBackground:withObject: . 另外,假设您不关心该方法在哪个后台线程上运行,则简单地使用performSelectorInBackground:withObject:会容易得多。 For example: 例如:

[self performSelectorInBackground:@selector(func1:) withObject:nil];

Try the following if it works: 如果可行,请尝试以下方法:

[NSThread detachNewThreadSelector:@selector(func1) toTarget:self withObject:nil];

Since you are not passing any object to your "func1" (aka: your method doesn't have parameters) you don't need to put the ":" after its name. 由于您没有将任何对象传递给“ func1”(又称:方法没有参数),因此无需在名称后加上“:”。

If your func1 accepting one argument. 如果func1接受一个参数。 Then definitely it has to work with second approach which you used. 那么绝对必须使用您使用的第二种方法。 May be your fuc1 has no formal argument and still u calling in selector like this @selector(fuc1:) and passing object as a nil. 可能是您的fuc1没有形式参数,并且您仍在调用选择器,例如@selector(fuc1 :),并将对象作为nil传递。 so may be due to this reason it is not working. 因此可能是由于这个原因,它无法正常工作。 It can be one reason. 这可能是原因之一。 just try it if not. 如果没有,那就试试看。

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

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