且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 KVC 中使用通配符?

更新时间:2023-01-16 17:14:38

虽然我找不到使用您尝试的语法支持通配符的方法.我使用 Objective-C 运行时发现了这个迂回的方法!

Though I couldn't find a way to support wildcards using the syntax you were attempting. I found this roundabout method using the Objective-C runtime!

首先我们获取您要使用的类的所有属性

First we get all of the properties of the class you'd like to use

#import <objc/runtime.h>

unsigned int outCount;
objc_property_t *properties = class_copyPropertyList([MyClass class], &outCount);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:outCount];
for (int i = 0; i < outCount; i++)
{
    objc_property_t property = properties[i];
    const char *propName = property_getName(property);
    if(propName)
    {
        NSString *propertyName = [NSString stringWithUTF8String:propName];
        [array addObject:propertyName];
    }
}
free(properties);

然后过滤掉你真正想要的


Then filter out the ones you actually want

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF ENDSWITH '1'"];
[array filterUsingPredicate:predicate];

然后实际使用它们


Then actually use them

for (NSString *key in array)
    NSLog(@"%@", [testClass valueForKey:key]);