Skip to main content
 首页 » 操作系统

ios之在 Swift 中使用 sortedArrayUsingSelector

2024年01月01日57shanyou

嘿 stackoverflow 的人们,

我已经在 swift 中实现了这个类:

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:]

我是 Swift 的新手,已经检查过 Apple's official documentation which can be found here.

我尝试了几种语法变体(添加“:”或删除它们,将函数名称作为字符串传递或不传递……以及各种组合),但都没有帮助。

所以在我绝望的时候,我向你寻求帮助。

最好的问候,

一月

请您参考如下方法:

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

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