gpt4 book ai didi

ios - Swift 2.2 字符串文字选择器

转载 作者:搜寻专家 更新时间:2023-11-01 06:19:46 26 4
gpt4 key购买 nike

在更新之前我这段代码工作正常:

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:) 没有方法,只有一个属性名。

最佳答案

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

  • 必须使用 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)可以使用。

关于ios - Swift 2.2 字符串文字选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com