方法基本
//3.创建模型对象
for ele in tweetNodes {
let model = TweetModel()
model.id = ele.elementsForName("id").last?.stringValue()
model.portrait = ele.elementsForName("portrait").last?.stringValue()
model.author = ele.elementsForName("author").last?.stringValue()
model.authorid = ele.elementsForName("authorid").last?.stringValue()
model.body = ele.elementsForName("body").last?.stringValue()
model.attach = ele.elementsForName("attach").last?.stringValue()
model.appclient = ele.elementsForName("appclient").last?.stringValue()
model.commentCount = ele.elementsForName("commentCount").last?.stringValue()
model.pubDate = ele.elementsForName("pubDate").last?.stringValue()
model.imgSmall = ele.elementsForName("imgSmall").last?.stringValue()
model.imgBig = ele.elementsForName("imgBig").last?.stringValue()
model.likeCount = ele.elementsForName("likeCount").last?.stringValue()
model.isLike = ele.elementsForName("isLike").last?.stringValue()
model.likeList = ele.elementsForName("likeList").last?.stringValue()
//id portrait author authorid body attach appclient commentCount pubDate imgSmall imgBig likeCount isLike likeList
self.dataArray.addObject(model)
}
2,方法 好用
func parseModel(element: GDataXMLElement, nameArray: Array<String>) -> TweetModel {
let model = TweetModel()
for name in nameArray {
let value = element.elementsForName(name).last!.stringValue()
//构造setter方法
//id -> setId:
//name -> setName:
let index = name.startIndex.successor()
let setterName = String(format: "set%@%@:", name.substringToIndex(index).capitalizedString, name.substringFromIndex(index))
print(setterName)
//字符串转换成方法
let sel = NSSelectorFromString(setterName)
model.performSelector(sel, withObject: value)
}
return model
}
//upper 调用
for ele in tweetNodes {
let nameArray = ["id", "portrait", "author", "authorid", "body", "attach", "appclient", "commentCount", "pubDate", "imgSmall", "imgBig", "likeCount", "isLike", "likeList"]
let model = self.parseModel(ele, nameArray: nameArray)
self.dataArray.addObject(model)
}
3, 方 法 +
func parseModel(element: GDataXMLElement, nameArray: Array<String>, className: String) -> NSObject {
//创建对象
//Class
let cls = NSClassFromString(className) as! NSObject.Type
let model = cls.init()
for name in nameArray {
let value = element.elementsForName(name).last!.stringValue()
//构造setter方法
//id -> setId:
//name -> setName:
let index = name.startIndex.successor()
let setterName = String(format: "set%@%@:", name.substringToIndex(index).capitalizedString, name.substringFromIndex(index))
//print(setterName)
//字符串转换成方法
let sel = NSSelectorFromString(setterName)
model.performSelector(sel, withObject: value)
}
return model
}
//upper 调用
for ele in tweetNodes {
let nameArray = ["id", "portrait", "author", "authorid", "body", "attach", "appclient", "commentCount", "pubDate", "imgSmall", "imgBig", "likeCount", "isLike", "likeList"]
let model = self.parseModel(ele, nameArray: nameArray, className: "_3_TestOSChina.TweetModel")
self.dataArray.addObject(model)
}