在Swift中使用数组对象的谓词返回错误

时间:2015-06-25 11:56:47

标签: swift nspredicate key-value-coding

当我使用Predicate过滤自定义Swift类的数组时,我得到错误:

  

*** NSForwarding:警告:对象0x78ed21a0类' Plantivo1_6.Seed'没有实现methodSignatureForSelector: - 前方麻烦   无法识别的选择器 - [Plantivo1_6.Seed valueForKey:]

如果我没记错的话,这可以在Objective-C中使用。我的错是什么?

let names = ["Tom","Mike","Marc"]
println(names)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", "om")
let array = (names as NSArray).filteredArrayUsingPredicate(searchPredicate)
println(array)
println()

let mySeed1 = Seed()  // Seed is a class with a `culture` String property
let mySeed2 = Seed()
let mySeed3 = Seed()
mySeed1.culture = "Tom"
mySeed2.culture = "Mike"
mySeed3.culture = "Marc"

let mySeeds = [mySeed1,mySeed2,mySeed3]
println(mySeeds)
let searchPredicate1 = NSPredicate(format: "SELF.culture CONTAINS[c] %@", "om")
let array1 = (mySeeds as NSArray).filteredArrayUsingPredicate(searchPredicate1)
println(array1)

4 个答案:

答案 0 :(得分:12)

您的Seed类是否继承自NSObject?

如果没有,这就是你将得到的信息。

解决方案:

class Seed: NSObject {
   ...

修改 stklieme是正确的 - 要使用NSPredicate,您的对象的类需要实现NSKeyValueCoding protocol定义的-valueForKey。您可以定义自己的-valueForKey实现,也可以让您的类继承自NSObject,它会为您处理。

这在the Apple docs for NSPredicate

中定义
  

您可以将谓词与任何类对象一起使用,但该类必须支持您要在谓词中使用的键的键值编码。

答案 1 :(得分:3)

如果您不想继承NSObject,可以自行实施value(forKey key: String) -> Any?方法:

extension Model {
    @objc func value(forKey key: String) -> Any? {
        switch key {
        case "id":
            return id
        // Other fields
        default:
            return nil
        }
    }
}

注意方法的@objc前缀:这很重要,因为它允许NSPredicate看到方法已实现。如果没有它,你仍然会收到does not implement methodSignatureForSelector:崩溃。

或者,更好的是,使您的对象符合此协议:

@objc protocol UsableInPredicate {
    @objc func value(forKey key: String) -> Any?
}

答案 2 :(得分:1)

valueForKey是一种关键值编码方法。将Seed类声明为NSObject的子类,它符合KVC

答案 3 :(得分:0)

简单地说,

您需要通过NSObject继承您的模型类,并解决您的问题。

public partial class Node : UserControl
{
    #region Position
    public static readonly DependencyProperty PositionProperty =
        DependencyProperty.Register("Position", typeof(Point), typeof(Node));

    public Point Position
    {
        get { return (Point) GetValue(PositionProperty); }
        set { SetValue(PositionProperty, value); }
    }
    #endregion Position

    public Node()
    {
        InitializeComponent();
    }

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        // Implementation skipped for brevity, together with OnMouseMove this controls Position
    }

    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        // Implementation skipped for brevity
    }
}

<强>原因: -valueForKey由NSKeyValueCoding协议定义。您可以定义自己的-valueForKey实现,也可以让您的类继承自NSObject