Is it possible to use a wildcard in KVC?

前端 未结 2 834
星月不相逢
星月不相逢 2021-02-06 16:37

I\'m trying to use wildcard in KVC like this.

Is it possible?

Or Is there other ways to use a wildcard to indicate a member variable?

@interface          


        
2条回答
  •  暖寄归人
    2021-02-06 16:53

    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 
    
    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]);
    

提交回复
热议问题