是否可以在 KVC 中使用通配符? [英] Is it possible to use a wildcard in KVC?

查看:67
本文介绍了是否可以在 KVC 中使用通配符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样在 KVC 中使用通配符.

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

有可能吗?

或者有其他方法可以使用通配符来表示成员变量吗?

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

使用通配符

MyClass *testClass = [[[MyClass alloc] init] autorelease];
testClass.test1 = @50;

NSLog(@"test value : %@", [testClass valueForKey:@"*1"]);

详细代码.

我想要的一个真正原因是通过整数或 nsnumber 类型的值来指示实例的成员变量.如果可能,更容易设置和读取任何实例的值.

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.

例如属性部分副本.

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

推荐答案

虽然我找不到使用您尝试的语法支持通配符的方法.我使用 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]);

这篇关于是否可以在 KVC 中使用通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆