【问题标题】:Get all NSArrays within an NSArray that contains a specific Key获取包含特定 Key 的 NSArray 中的所有 NSArray
【发布时间】:2014-09-01 13:07:58
【问题描述】:

我有一个输出以下内容的 NSArray:

(
    {
    category = 1;
    categoryname = Random;
    excuse = "Enter your excuse here";
    id = 1;
    name = Jo;
},
    {
    category = 2;
    categoryname = School;
    excuse = "Enter your excuse here";
    id = 2;
    name = Jo;
},
    {
    category = 2;
    categoryname = School;
    excuse = "Enter your excuse here";
    id = 3;
    name = if;
}
)

现在您可以看到,category 有不同的值。我正在传递一个Int,我想将它与category 值进行比较,以便仅检索另一个NSArray 中某个类别中的那些对象。

这是我的代码:

func getAllExcusesData(categoryID: Int) -> NSMutableArray {
    var arr: NSMutableArray = NSMutableArray()
    for excuse in allExcusesData {
        println(excuse["category"]) // this line outputs "Optioanl(x)" - x is either 1 or 2, depending on what index I pass through
// it crashes here, at the 'if' line
        if excuse["category"] as Int == categoryID {
            var e: NSArray = excuse as NSArray
            arr.addObject(excuse)
        }
    }
    return arr
}

它在if 行崩溃,但它确实给出了错误: Thread 1:EXC_BREAKPOINT(code=EXC_1386_BPT, subcode=0x0)

如何将对象中的 category 字段与给定索引进行比较,然后将其添加到将从方法返回的新数组中?

【问题讨论】:

    标签: casting swift nsarray


    【解决方案1】:

    下标返回AnyObject? 的可选值 - 您必须在强制转换之前将其解包或通过以下方式之一与另一个值进行比较:

    if let excuseCategory: AnyObject = excuse["category"]? {
        if excuseCategory as Int == categoryID {
            // do sth
        }
    }
    
    // or if you're absolutely sure that "category" key always exists:
    
    if excuse["category"]! as Int == categoryID {
        // do sth
    }
    

    考虑到ArrayNSArrayNSMutableArray 之间的桥梁,您可以“快速化”您的代码:

    func getAllExcusesData(categoryID: Int) -> NSArray {
        return (allExcusesData as [AnyObject]).filter({ excuse in
            return excuse["category"]! as Int == categoryID
        })
    }
    

    【讨论】:

    • 给出完全相同的错误,它位于excuse["category"]! as Int 行。而且我知道有那个键,因为我可以事先打印出来
    • excuse["category"] 可能是一个字符串
    • 当您尝试在 Swift 中使用 NSArray 时会发生这种情况。
    • 试试if excuse["category"]! as String == "\(categoryID)"
    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2013-02-07
    相关资源
    最近更新 更多