Swift 2.2字符串文字选择器

时间:2016-03-25 11:18:49

标签: ios swift cocoa uilocalizedcollation

在更新之前,我的代码运行良好:

var alphabetizedArray = [[Person]]()

    let collation = UILocalizedIndexedCollation()

    for person : Person in ContactsManager.sharedManager.contactList {
        var index = 0
        if ContactsManager.sharedManager.sortOrder == .FamilyName {
            index = collation.sectionForObject(person, collationStringSelector: "lastName")
        }
        else {
            index = collation.sectionForObject(person, collationStringSelector: "firstName")
        }
        alphabetizedArray.addObject(person, toSubarrayAtIndex: index)
    }

但是现在由于字符串文字选择器不再被赋予代码,因此代码破坏了。

我尝试将字符串文字选择器更改为Selector(" lastName"),但是'索引'始终返回-1。而且我没有看到任何解决方案。

此归类方法采用给定对象的属性名称。而Person类确实有这些属性(lastName,firstName)。

但我怎样才能再次完成这项工作?使用#selector进行的实验没有给我任何信息:'' #selector'不是指初始化者或方法'它说。难怪因为这个sectionForObject(,collat​​ionStringSelector :)不采用任何方法而是属性名称。

2 个答案:

答案 0 :(得分:4)

这似乎是几个问题的组合:

  • 必须使用UILocalizedIndexedCollation.currentCollation()创建排序规则。
  • 对象类需要实例方法返回String
  • #selector必须引用该实例方法,#selector(<Type>.<method>)#selector(<instance>.<method>)都可以使用。

这是一个自包含的示例,似乎按预期工作:

class Person : NSObject {
    let firstName : String
    let lastName : String

    init(firstName : String, lastName : String) {
        self.firstName = firstName
        self.lastName = lastName
    }

    func lastNameMethod() -> String {
        return lastName
    }
}

然后

let person = Person(firstName: "John", lastName: "Doe")
let collation = UILocalizedIndexedCollation.currentCollation()
let section = collation.sectionForObject(person, collationStringSelector: #selector(Person.lastNameMethod))
print(section) // 3

此处,#selector(Person.lastNameMethod)#selector(person.lastNameMethod)均可使用。

答案 1 :(得分:0)

首先阅读有关Swift2.2中选择器的新文档来解决您的问题。

示例:使用#selector(CLASS.lastName)代替Selector("lastName")。在CLASS中,它是包含此方法的实际类。