我目前正在做一个项目,在这个项目中,用户在NSDictionnary中定义了一些参数,我正在用它来设置一些对象。例如,您可以要求创建一个Sound对象,其参数为param1=xxx、param2=yyy、gain=3.5 ...然后是一个带有参数speed=10、active=YES、name=zzz的Enemi对象...
{
active = NO;
looping = YES;
soundList = "FINAL_PSS_imoverhere_all";
speed = 100.0;}
然后,我实例化我的类,并希望从这个字典中自动设置ivars。我实际上已经写了一些代码来检查这个参数是否存在,但我在实际设置参数值时遇到了问题,特别是当参数为非对象(浮点型或布尔型)时。
到目前为止,我正在做的是:
//aKey is the name of the ivar
for (NSString *aKey in [properties allKeys]){
//create the name of the setter function from the key (parameter -> setParameter)
NSString *setterName = [aKey stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[aKey substringToIndex:1] uppercaseString]];
setterName = [NSString stringWithFormat:@"set%@:",setterName];
SEL setterSelector = NSSelectorFromString(setterName);
//Check if the parameter exists
if ([pge_object respondsToSelector:setterSelector]){
//TODO : automatically set the parameter
}
else{
[[PSMessagesChecker sharedInstance]logMessage:[NSString stringWithFormat:@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]] inColor:@"red"];
NSLog(@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]);
}
}
}如你所见,一旦我发现这个参数存在于对象上,我不知道该怎么做。我尝试使用"performSelector... withObject...,但我的问题是一些参数是非对象的(浮点型或布尔型),我还试图通过使用setter来获取参数的类,但没有帮助。
有没有人成功做到了这样的事情?
发布于 2012-11-29 01:29:57
杰克·劳伦斯的评论恰到好处。你要找的是Key Value Coding,或者就是KVC。Cocoa的这一基本部分允许您使用名称作为字符串和新值来获取和设置任何实例变量。
它将自动处理强制对象为原始值,因此您也可以将其用于int和float属性。
还支持验证值和处理未知属性。
see the docs
您的代码无需验证即可编写
for( id eachKey in props ) {
[anOb setValue:props[eachKey] forKey:eachKey];
}或者只是
[anOb setValuesForKeysWithDictionary:props];就像杰克说的。
发布于 2012-11-29 01:29:10
对于非对象参数,您必须将它们放入对象中,例如NSNumber或NSValue。然后,您可以将这些对象添加到字典中。
例如:
float f = 0.5;
NSNumber f_obj = [NSNumber numberWithFloat:f];https://stackoverflow.com/questions/13609924
复制相似问题