利用NSInvocation对方法进行抽象,实现对方法的加锁

简介:

我们在实际开发中须要对离散的方式加锁实现线程安全,当然我们有多种实现方式,这仅仅是当中一种,使用起来比較方便


+ (id)performSelectorWithTarget:(id)target selector:(SEL)selector withObject:(id)arg1 ,...NS_REQUIRES_NIL_TERMINATION;

{

    @synchronized(self){

        id result = nil;

        NSMethodSignature *sig = [target methodSignatureForSelector:selector];

        if (!sig) return result;

        

        NSInvocation* myInvocation = [NSInvocation invocationWithMethodSignature: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 = va_arg(args,id)) {

            [myInvocation setArgument:&obj atIndex:argumentStart];

            argumentStart++;

        }

        

        va_end(args);

        

        [myInvocation retainArguments];

        [myInvocation invoke];

        

        //获得返回值类型

        const char *returnType = sig.methodReturnType;

        

        //声明返回值变量

        //假设没有返回值,也就是消息声明为void,那么returnValue=nil

        

        if( !strcmp(returnType, @encode(void)) ){

            

            result =  nil;

        }

        

        //假设返回值为对象。那么为变量赋值

        else if( !strcmp(returnType, @encode(id)) ){

            [myInvocation getReturnValue: &result];

        }else{

            

            //假设返回值为普通类型NSInteger  BOOL

            //返回值长度

            

            NSUInteger length = [sig methodReturnLength];

            

            //依据长度申请内存

            void *buffer = (void *)malloc(length);

            

            //为变量赋值

            

            [myInvocation getReturnValue:buffer];

            

            if( !strcmp(returnType, @encode(BOOL)) ) {

                

                result = [NSNumber numberWithBool:*((BOOL*)buffer)];

            }

            else if( !strc


mp(returnType, @encode(NSInteger)) ){

                

                result = [NSNumber numberWithInteger:*((NSInteger*)buffer)];

            }else {

                result = [NSValue valueWithBytes:buffer objCType:returnType];

            }

            

            free(buffer);

        }

        return result;

    }

}





本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5283683.html,如需转载请自行联系原作者

相关文章
|
8月前
|
安全
架构系列——通过ReentrantLock源码分析给对象上锁的原理
架构系列——通过ReentrantLock源码分析给对象上锁的原理
|
1月前
|
存储 安全 Java
|
2月前
|
存储 安全
除了Lock对象,还有其他方法可以实现多线程安全的单例模式吗?
【2月更文挑战第5天】【2月更文挑战第12篇】除了Lock对象,还有其他方法可以实现多线程安全的单例模式吗?
|
4月前
|
存储 C++ 容器
C++中的继承机制
C++中的继承机制
|
9月前
|
安全 Java API
原子操作类解读
原子操作类解读
原子操作类解读
|
9月前
|
安全 搜索推荐
如何避免写重复代码?两种常见的方法:抽象和组合
如何避免写重复代码?两种常见的方法:抽象和组合
151 0
|
9月前
|
缓存 Linux 容器
深入了解锁细节
深入了解锁细节
43 0
|
关系型数据库 索引
上手隐式锁,显式锁
上手隐式锁,显式锁
上手隐式锁,显式锁
|
C++
C++继承机制
C++继承机制
69 0
|
安全
【多线程:转账例子】探究两个对象对应两个线程如何加锁
【多线程:转账例子】探究两个对象对应两个线程如何加锁
241 0

热门文章

最新文章