iOS如何使用谓词或KVC将对象的多个属性转储到字典中?

iOS如何使用谓词或KVC将对象的多个属性转储到字典中?,第1张

概述我有一个带有属性膨胀的类,现在大约有30个,其中大多数是整数枚举类型. 我的代码目前在很多地方使用它,我试图轻轻地移动到新的字典表示. 我正在寻找从这个对象创建一个字典,但只包括非0的值(具有一些数据的值). 是否有一些Objective-c键值编码魔术可以帮助我简化这种方法的编写? @property(nonatomic)kGrade grade;@property(nonatomic)kQu 我有一个带有属性膨胀的类,现在大约有30个,其中大多数是整数枚举类型.

我的代码目前在很多地方使用它,我试图轻轻地移动到新的字典表示.

我正在寻找从这个对象创建一个字典,但只包括非0的值(具有一些数据的值).

是否有一些Objective-c键值编码魔术可以帮助我简化这种方法的编写?

@property(nonatomic)kGrade grade;@property(nonatomic)kQuality quality;//a whole bunch more propertIEs    -(NSMutableDictionary*)itemAsDictionary    {        if(itemDictionary !=nil)        {            return itemDictionary;        }else        {            itemDictionary = [[NSMutableDictionary alloc] initWithCapacity:40];            //I really dont want to write a whole bunch of such statements            if(self.grade>0)            {                [itemDictionary setobject:@(self.grade) forKey:@"grade"];            }            //add 39 other items        }        return itemDictionary;    }
解决方法
- (NSMutableDictionary *)itemAsDictionary{    NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];    unsigned int outCount,i;    //type the name of the class you want to turn to dictionary    objc_property_t *propertIEs = class_copyPropertyList([Item class],&outCount);    for (i = 0; i < outCount; i++) {        objc_property_t property = propertIEs[i];        const char *propname = property_getname(property);        if (propname) {            Nsstring *propertyname = [Nsstring stringWithUTF8String:propname];            ID propertyValue = [self valueForKey:propertyname];            //set up the filter here            if([propertyValue isKindOfClass:[NSNumber class]] && [propertyValue intValue] > 0)            {                [resultDic setobject:propertyValue forKey:propertyname];            }else if(![propertyValue isKindOfClass:[NSNumber class]] && propertyValue !=nil)            {                //copy all non-nil variables                [resultDic setobject:propertyValue forKey:propertyname];            }        }    }    free(propertIEs);    return resultDic;}

我尝试从一个类中获取属性列表然后返回一个字典,它已经工作了.你可以尝试一下.

编辑:如果我在子类中使用[self class],上面的代码不起作用,但是当我用[Item class]替换self时确实有效.

我添加了几个简单的检查 – 我对大于0的数字和非零属性感兴趣,比如字符串和图像.请注意,如果我删除第二个数字检查,代码将在结果字典中放置零.

总结

以上是内存溢出为你收集整理的iOS如何使用谓词或KVC将对象的多个属性转储到字典中?全部内容,希望文章能够帮你解决iOS如何使用谓词或KVC将对象的多个属性转储到字典中?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1040149.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存