iOS 將對象的屬性和屬性值拆分成key、value,通過字符串key來獲取該屬性的值


  這篇博客光看標題或許就會產生疑問,某個對象,只要它存在某個屬性,且值不是空的,不就能直接用點方法獲取嗎,為什么要拆分成key和value多此一舉呢?下面,我用一個例子告訴大家,既然這方法是存在的,那就有它存在的價值。

      有一個對象,比如說是倉庫清單:model。蘋果:100斤,香蕉:50斤,梨子:80斤。。。。。。。。(共50種貨物)

      現在我要建立一個tableView表格,一個分區,50個單元格,每個cell的內容是:貨物種類    存有多少

      cell肯定是根據IndexPatch.row來取值的,row對應的數組便是kindArr:["蘋果","香蕉","梨子",......](長度為50)

      在cell的代理函數中,我們不可能這么寫:lable.text = model.kindArr[IndexPatch.row],絕對報錯,問題就來了,如何把字符串轉化成對象的屬性呢?這個問題估計找很久都是竹籃打水。

      所以這里換個思維,將對象的屬性和屬性值拆分成key、value,代碼如下(Swift):

func getValueByKey(key:String) ->String{
        let hMirror = Mirror(reflecting: model)
        for case let (label?, value) in hMirror.children{
            if (label == key) {
                return value as! String;
            }
        }
        return "";
    }

      如此,cell里的代碼就是lable.text = getValueByKey(key:kindArr[IndexPatch.row])

      這邊順便復制過來一份OC的代碼:iOS 獲取對象的全部屬性、把model的所有屬性和對應的值轉化為字典(網址:http://blog.csdn.net/moxi_wang/article/details/50740708)

//獲取對象的所有屬性
- (NSArray *)getAllProperties
{
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([self class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++)
    {
        const char* propertyName =property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    free(properties);
    return propertiesArray;
}

//Model 到字典
- (NSDictionary *)properties_aps
{
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}

 

 

 

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM