【问题标题】:Using sortedArrayUsingSelector in Swift在 Swift 中使用 sortedArrayUsingSelector
【发布时间】:2015-01-07 19:29:27
【问题描述】:

大家好,stackoverflow,

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

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:警告:对象 'SwiftColorArt.PCCountedColor' 类的 0x7fd391b25a50 不 实现 methodSignatureForSelector: -- 前面的麻烦 Unrecognized 选择器 -[SwiftColorArt.PCCountedColor 比较:]

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

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

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

最好的问候,

一月

【问题讨论】:

标签: ios sorting swift nsarray unrecognized-selector


【解决方案1】:

"SwiftColorArt.PCCountedColor' 没有实现 methodSignatureForSelector: -- 前面的麻烦 Unrecognized selector -[SwiftColorArt.PCCountedColor compare:]"

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

【讨论】:

  • 公平地说,它并没有字面意思说明...:P
  • 好吧,好吧,它告诉该做什么。 :) 但实际上,我同意你的看法,@akashivskyy - 如果可以避免的话,OP 一开始就不应该调用这个方法。 Swift 具有出色的原生数组排序功能。
  • 谢谢 - 这有帮助!我目前正在尝试通过将github.com/fleitz/ColorArt(它是用Objective-C 编写的,我也不知道)移植到swift 来学习swift。 @akashivskyy - 我一定会调查的!
  • 祝你好运!请务必观看一些 WWDC 会议,它们是初学者的绝佳学习资源。
  • @JanGregorTriebel 你正在做的事情与我在学习时所做的事情相同。首先,我将我现有的应用程序从 Objective-C 直接翻译成 Swift。然后我重新设计了它们,使它们更加 Swifty。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 2016-05-26
相关资源
最近更新 更多