2015-01-07 155 views
1

嘿计算器的人使用sortedArrayUsingSelector,在斯威夫特

我已经迅速实现了这个类:

class PCCountedColor { 

    var color:UIColor 
    var count:Int 

    init (color:UIColor, count:Int) 
    { 
     self.color = color; 
     self.count = count; 
    } 

    func compare(object:PCCountedColor) -> NSComparisonResult 
    { 
     if (self.count < object.count) 
     { 
      return NSComparisonResult.OrderedDescending 
     } 
     else if (self.count == object.count) 
     { 
      return NSComparisonResult.OrderedSame 
     } 

     return NSComparisonResult.OrderedAscending 
    } 
} 

然后,我有这充满以上的类的对象一个NSMutableArray:

var sortedColors:NSMutableArray = [] 
var container:PCCountedColor = PCCountedColor(color:curColor, count: colorCount) 
sortedColors.addObject(container) 

之后,我尝试通过上面的类中的特殊功能对数组进行排序:

sortedColors.sortedArrayUsingSelector(Selector("compare:")) 

但我得到的是一个错误:

SwiftColorArt[1584:42892] *** NSForwarding: warning: object 0x7fd391b25a50 of class 'SwiftColorArt.PCCountedColor' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector -[SwiftColorArt.PCCountedColor compare:]

我是新雨燕已经检查Apple's official documentation which can be found here.

我曾尝试多种语法变体(加“:”或将其删除,通函数名称作为一个字符串或不...以及各种组合),但没有一个帮助。

所以在我的绝望中,我转向你寻求帮助。

最好的问候,

+0

可能与此处相同的问题:http://stackoverflow.com/questions/24415662/object-x-of-class-y-does-not-implement-methodsignatureforselector-in-swift。 –

+0

你应该***使用[Swift的'sort'函数](https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Array.html#//apple_ref/ DOC/UID/TP40014608-CH5-SW48)。 – akashivskyy

回答

3

"SwiftColorArt.PCCountedColor' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector -[SwiftColorArt.PCCountedColor compare:]"

错误消息告诉你该怎么做。使这个类成为NSObject的一个子类,一切都会好的。

+0

公平地说,它不会*字面上*告诉我...... P – akashivskyy

+0

好吧,它告诉_me_该做什么。 :)但是,真的,我同意你的看法,@akashivskyy - 如果可以避免,OP不应该首先调用这个方法。 Swift具有用于排序数组的优秀本机功能。 – matt

+0

谢谢 - 这有帮助!我目前正试图通过移植https://github.com/fleitz/ColorArt(它是用Objective-C编写的,我也不知道)迅速学习。 @akashivskyy - 我会确保看看! – Jan