1

我的应用程序中有一个包含各种类别的侧面菜单,例如:“所有帖子,国际,国家等”。现在我从 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 数据,并在我的表格视图中只加载属于相应侧菜单条目的数据。

4

1 回答 1

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)
    }
}
于 2015-10-20T14:56:43.333 回答