【发布时间】:2015-05-06 22:42:53
【问题描述】:
我正在编写一个通用方法,它采用字典和给定类型的参数来构建对象。
例如,如果您发出 SOAP 请求以获取电影并将响应存放在 Dictionary 中,您可以:
var movie : Movie = myGenericMethod(dic : Dictionary, objectToIntrospect : Movie()) as Movie
适用于:
- 简单对象
- 复杂对象
但是如果你有一个对象数组,我就有问题了。 所以想象你的电影对象包含一个演员数组......
通过反射,我得到了我班级的所有类型的属性。 有了这个,我构建了一个包含我的类型的任何对象的数组。 例如,一个对象包含在其他对象(电影中的演员)中:
//All type of attributes of my movie object, at index [i] i have my "Actor" object
var anyType : Any = typesOfProperties[i]
//I cast it in object
var objectType : NSObject = anyType as NSObject
//Dont worry about this method, it's just for get the dictionary
var otherDico : NSDictionary = ConverterUtilities.extractDictionaryFromOtherDictionary(dict, dicoName: property, soapAction: soapAction) as NSDictionary
//I build the Actor object with the data of the dictionary. objectType.self give the Actor type
var propertyObject: NSObject = self.buildAnyObjectWithDictionary(otherDico, soapAction: "", objectToIntrospect:objectType.self) as NSObject
//I set the property Actor in my Movie object (myObjectToReturn)... The "property" parameter is the key
ConverterUtilities.setPropertyValue(property, value: propertyObject, objectToReturn : myObjectToReturn, isObject : true)
它工作得很好......如果我的电影对象中只有一个演员,“propertyObject”将是一个演员类型,这导致 objectType 是一个演员对象。
但是,如果我有一个数组,我会在处理 Array 的方法中重定向,我的 objectType 返回“Swift._NSSwiftArrayImpl”,我的 anyType 对象返回“([myproject.Actor])”。 我不需要知道这只是一个数组,因为我知道。但我需要知道这是一个 Actor 数组,用于动态构建一些 Actor 对象!
这是我目前拥有的:
var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic, soapAction: "", objectToIntrospect: Actor()) as NSObject
arraySpecific.append(objToAdd)
如您所见,如果我对类型进行硬编码,这将非常有效。但我需要让它像前面的例子一样!像这样:
var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic, soapAction: "", objectToIntrospect: anObjectWithActorType) as NSObject
arraySpecific.append(objToAdd)
(第一版和第二版的区别在于objectToIntrospect参数)
你知道如何使用我的 Any 对象(包含:([myproject.Actor]) 来构建一个 Actor 的实例吗?
我真的需要你的帮助!问候!
PS:对不起我的英语不好,希望你能理解我:)
【问题讨论】:
标签: arrays swift types generics