We need to be in the actual development of a discrete way to lock the thread safety, of course, we have a variety of implementation, this is just one of the more convenient to use.
+ (ID) performselectorwithtarget: ( ID target selector: (SEL) selector withobject: (ID) arg1,... ns_requires_nil_termination ;
{
@synchronized(self) {
ID result =nil;
nsmethodsignature *sig = [targetmethodsignatureforselector: selector];
if (!sig)return result;
nsinvocation* myinvocation = [nsinvocationinvocationwithmethodsi Gnature: sig];
[myinvocation settarget: target];
[myinvocation setselector: selector];
int argumentstart =2;
va_list args;
va_start(args, arg1); //scan for arguments after firstobject.
//Get rest of the objects until nil is found
for (id obj = arg1; obj! =nil; obj = V A_arg(args,ID)) {
[myinvocation setargument: &objatindex: Argumentstart];
argumentstart++;
}
va_end(args);
[myinvocation retainarguments];
[myinvocation invoke];
// Get return value type
constchar *returntype = sig. Methodreturntype ;
// Declare return value variable
// If there is no return value, that is, the message is declared void, then returnvalue=nil
if(! strcmp (ReturnType,@encode(void))) {
result = Nil ;
}
// If the return value is an object, assign a value to the variable
Elseif(! strcmp (ReturnType,@encode(ID))) {
[myinvocation getreturnvalue: &result];
}else{
// If the return value is normal type nsinteger BOOL
// return value length
nsuinteger length = [sigmethodreturnlength];
// request memory by length
void *buffer = (void *)malloc(length);
// Assign a value to a variable
[myinvocation getreturnvalue: buffer];
if(! strcmp (ReturnType,@encode(BOOL))) {
result = [nsnumbernumberwithbool:* ((BOOL ( *) buffer)];
}
Elseif(! strcmp (ReturnType,@encode(nsinteger))) {
result = [nsnumbernumberwithinteger:* (Nsinteg ER*) (buffer)];
}else {
result = [nsvaluevaluewithbytes: Buffer objctype: ReturnType];
}
free(buffer);
}
return result;
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using Nsinvocation to abstract the method and realize the lock-up of the method