'#selector'的参数不是指初始化器或方法

时间:2016-12-06 07:21:17

标签: ios swift3 xcode8.1

我将项目从Swift2.2更新为Swift3.0但收到"Argument of '#selector' does not refer to an initializer or method"个问题。

以下是代码

for object in Students {
    let sectionNumber = collation.section(for: object.firstName!, collationStringSelector: #selector(NSObjectProtocol.self))
    sections[sections.count - 1 - sectionNumber].append(object)
}

enter image description here

3 个答案:

答案 0 :(得分:3)

class Person: NSObject {
    @objc var name: String

    init(name: String) {
        self.name = name
    }
}

let p = Person(name: "Alice")

let collation = UILocalizedIndexedCollation.current()
collation.section(for: p, collationStringSelector: #selector(getter: Person.name))

这也很好,因为Selector来自Objective-C。我们需要:NSObject@objc

答案 1 :(得分:0)

根据文档

func section(for object: Any, collationStringSelector selector: selector) -> Int

Description 
Returns an integer identifying the section in which a model object belongs.
The table-view controller should iterate through all model objects for the table view and call this method for each object. If the application provides a Localizable.strings file for the current language preference, the indexed-collation object localizes each string returned by the method identified by selector. It uses this localized name when collating titles. The controller should use the returned integer to identify a local “section” array in which it should insert object.

Parameters  
object
A model object of the application that is part of the data model for the table view.

*selector*
A selector that identifies a method returning an identifying string for object that is used in collation. The method should take no arguments and return an NSString object. For example, this could be a name property on the object.

Returns 
An integer that identifies the section in which the model object belongs. The numbers returned indicate a sequential ordering.

<强>解决方案

如下所示改变

collation.section(for: "test", collationStringSelector: #selector(getStr)) //here getStr is an other function returning String



func getStr()->String{
        return "test"; // this should return an identifying string for object that is used in your collation
}

答案 2 :(得分:0)

我实现了user2215977的答案,但app再次崩溃&amp;再次。现在我只需将#selector(NSObjectProtocol.self)更改为“self”。所有错误都消失但只收到一条警告“不推荐使用Objective-C选择器的字符串文字;请改用#selector”。

如果有人想知道解决此警告,请与我分享。否则现在出错。