IOS_利用反射獲得類中的屬性列表和Demo分享

感謝本羣 【天空air_as3_北京】 兄弟的投稿,當天說分享,馬上就發來了,還附上完整的Demo代碼


下面是該兄的分享內容:


反射的原理,是對我們創建對象的探知、自審。作用簡單的說就是可以動態加載和處理一些事務。


【天空air_as3_北京】寫的代碼片段:
 +(Tween *)to:(UIView *)target duration:(float)dur vars:(NSObject *)params tweenName:(NSString *)tweenName
{
    if(target == nil) return nil;
    
    if (!all) {
        all = [[NSMutableDictionary alloc] init];
    }
    
    id tweenParamsClass = [params class];
    
    unsigned int count,i;
    
    objc_property_t *properties = class_copyPropertyList(tweenParamsClass,&count);
    objc_property_t p;
    
    Tween *t = [[Tween alloc] init];
    
    NSMutableArray *propNames = [[NSMutableArray alloc] init];
    NSMutableArray *propValues = [[NSMutableArray alloc] init];
    
    for (i = 0; i<count; i++)
    {
        p = properties[i];
        
        NSString *propName = [NSString stringWithUTF8String:property_getName(p)];
        
        id value = [params valueForKey:propName];
        if(value)
        {
            [propNames addObject:propName];
            [propValues addObject:value];
        }


    }
    
    free(properties);
    
    [t createTween:target propNameAry:propNames propAry:propValues tweenName:tweenName];
  
    return t;
}


    
/***********************華麗的分割線********************************/

補充幾個反射的使用情景,僅供參考

SEL selector = NSSelectorFromString(@"testMethod:");

NSObject obj = ...;

1、[object performSelector:selector  withObject:@"param"]

2、IMP imp = [[My Classclass] instanceMethodForSelector:selector];

     imp(obj, selector, @"param");

3、objc_msgSend(obj,tempSel,@"12345");

4、NSInvocation


在ios直接調用某個對象的消息是方法有兩種:

1.performselector: withObject:  簡單的常用的調用方式

2.invocation  當參數>2個或者有返回值的時候,可能用這個會更便捷

NSInvocation可以處理參數和返回值,其實NSInvocation就相當於反射操作。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章