我有一个包含各种类别的侧边菜单,例如:“我的应用中的所有帖子,国际,国家等”。现在我从API接收数据并使用JSON解析它。此数据存储在NSDictionary
。
以下是代码:
import Foundation
class Member
{
let imageName: NSData!
let name: String?
let about: String?
let tag : String?
init(dictionary:NSDictionary)
{
let url = dictionary["imageUrl"] as? String
let imgdata = NSURL(string: url!)
imageName = NSData(contentsOfURL: imgdata!)
name = dictionary["title"] as? String
tag = dictionary["TAG"] as? String
// fixup the about text to add newlines
let unescapedAbout = dictionary["postBody"] as? String
about = unescapedAbout?.stringByReplacingOccurrencesOfString("\\n", withString:"\n", options:[], range:nil)
}
class func loadMembersFromFile(path: NSURL) -> [Member]
{
var members:[Member] = []
if let data = NSData(contentsOfURL: path),
// if let data = NSData(contentsOfFile: path, options:[]),
json = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)as? NSDictionary,
team = json["items"] as? [NSDictionary]{
for memberDictionary in team {
let member = Member(dictionary: memberDictionary)
members.append(member)
}
}
return members
}
}
现在JSON文件包含一个字段,如TAG =“international”,TAG =“national”等等。
我想根据上面的标记过滤这个JSON数据,只加载属于我的表视图中相应侧边菜单项的数据。
答案 0 :(得分:0)
在将“新”成员附加到数组
之前,您只需检查TAG的值for memberDictionary in team {
let member = Member(dictionary: memberDictionary)
guard let tag = member.tag as? String else {
continue
}
if tag == theTag { // Add a parameter 'theTag' (String) to your method
members.append(member)
}
}