Is it possible to use a wildcard in KVC?
objective-c
Solution
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]);
Problem
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 MyClass : NSObject @property(nonatomic, retain) NSNumber *test1; @property(nonatomic, retain) NSNumber *test2; @end @implementation MyClass{ NSNumber * test1; NSNumber * test2; } @synthesize test1; @synthesize test2; @end ``` using wildcard ``` MyClass *testClass = [[[MyClass alloc] init] autorelease]; testClass.test1 = @50; NSLog(@"test value : %@", [testClass valueForKey:@"*1"]); ``` For detail codes. A real reason i wanted is to indicate a member variable of instance by value of integer or nsnumber type. If possible, it is easier to set values and read values of any instance. For example of property part copy. ``` MyClass *testClass = [[[MyClass alloc] init] autorelease]; testClass.year_1 = @2012; testClass.quarter_2 = @3; testClass.month_3 = @8; testClass.day_4 = @20; testClass.week_5 = @4; // copy propertys to other instance. // Normal way MyClass *testClassCopy = [[[MyClass alloc] init] autorelease]; testClassCopy.year_1 = testClass.year_1; testClassCopy.quarter_2 = testClass.quarter_2; testClassCopy.month_3 = testClass.month_3; testClassCopy.day_4 = testClass.day_4; // copy propertys by using wildcard for (int j = 0; j < 4; j++) { NSString *indicate = [NSString stringWithFormat:@"*%@", [NSNumber numberWithInteger:j + 1]]; NSNumber *sourceProperty = [testClass valueForKey:indicate]; [testClassCopy setValue:sourceProperty forKey:indicate]; } ```