快速动态创建对象并设置属性 [英] Dynamically create objects and set attributes in swift
问题描述
我正在研究一个自定义方案,其中我需要在运行时创建一个已定义类的对象,并为其设置属性.在Objective-C中这样的事情
I am looking into a custom scenario wherein I need to create a object of a defined class during the run time and set attributes to it as well. Something like this in objective-C
//The Model class
@interface Car:NSObject
{
@property(nonatomic,copy) NSString * numberOfDoors;
@property(nonatomic,copy) NSString * carModel;
@property(nonatomic,copy) NSString * carMake;
@property(nonatomic,copy) NSString * carBrand;
}
为上述类创建一个自定义运行时对象(不确定这是否正确,只是从我的脑海中说出来)
Creating a custom run time object for the above class (not sure whether this is right but just speaking from the top of my head)
id myNewObject = [[NSClassFromString(@"Car") alloc]init];
[myNewObject setValue:@"4 doors" forKeyPath:@"numberOfDoors"];
[myNewObject setValue:@"Prius" forKeyPath:@"carModel"];
[myNewObject setValue:@"2014" forKeyPath:@"carMake"];
[myNewObject setValue:@"Toyota" forKeyPath:@"carBrand"];
因此,我的目的是创建一个对象映射模块,该模块将使用类名和对象映射信息,这些信息将描述如何从JSON响应中映射/创建模型对象(类似于RestKit减去核心数据)同步部分).
So my intention here is to create a object mapping module that would take the class name and a object mapping information that will describe how to map/create a model object from a JSON response (something very similar to RestKit minus the core data sync part).
我知道可以使用目标C来完成此操作,但不确定如何将它适用于Swift类
I know this can be done with objective C but not sure how this would be applicable to swift classes
感谢您的帮助.
推荐答案
我认为这就是您想要的:
I think that this is what you want:
@objc(MyClass)
class MyClass : NSObject {
var someProperty = 0
}
let type = NSClassFromString("MyClass") as! NSObject.Type
let instance = type()
instance.setValue(12, forKey: "someProperty")
这篇关于快速动态创建对象并设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!