问题
i have created a thread in xcode and i have given the function name to be called from that thread. 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.
so can any one please tell me how to create the thread and call func1 from there....
回答1:
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
. The empty thread variable is then sent to the performSelector:onThread:withObject:waitUntilDone:
method which will presumably do nothing.
You will need to properly create a thread before you can actually run something on it using 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:
. For example:
[self performSelectorInBackground:@selector(func1:) withObject:nil];
回答2:
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.
回答3:
If your func1 accepting one argument. 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. so may be due to this reason it is not working. It can be one reason. just try it if not.
来源:https://stackoverflow.com/questions/10427140/call-a-function-using-thread-in-xcode