当对象不存在时,ABRecordCopyValue不起作用 [英] ABRecordCopyValue not working when object doesn't exist
问题描述
当地址簿中没有姓氏的联系人时,Swift中的这行代码会导致我出现问题。
This line of code in Swift causes me problems when the address book has a contact with no last name.
我试图通过多种方式解决它无济于事。我可以使用某种try catch语句或错误处理吗?或者检查AnyObject是否为null(返回类型
I've tried to resolve it a number of ways to no avail. Is there some sort of try catch statement or error handling I can use? Or check if AnyObject is null (the return type of
ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue()).
我尝试使用可选类型,但由于应用程序停止运行,它似乎无法运行你选择一个没有姓氏的联系人的时刻 - 下面的代码行突出显示错误线程
I've tried using optional types but it doesn't seem to work since the app stops running the moment you select a contact with no last name - and the line of code below gets highlighted with the error Thread
1:EXC_BAD_ACCESS
1: EXC_BAD_ACCESS
let lName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as String
推荐答案
ABRecordCopyValue 实际上可以返回nil所以你应该打开它。另外,转换为String对我来说不起作用所以我正在使用NSString。
ABRecordCopyValue can actually return nil so you should unwrap it. Also, casting to String didn't work for me so I'm using NSString.
if let firstName = ABRecordCopyValue(abContact, kABPersonFirstNameProperty)?.takeRetainedValue() as? NSString {
println("FIRST NAME: \(firstName)")
}
else {
println("No Name")
}
您可以尝试的另一件事是,您可以尝试获取组合名称,而不是单独获取firstName和lastName。
Another thing you could try is instead of getting the first and lastName individually, you could also try to get the composed name.
if let fullName = ABRecordCopyCompositeName(abContact)?.takeRetainedValue() as String? {
println("Full Name: \(fullName)")
}
PS:我也尝试过所有答案这个问题但是尽管在调试应用程序时非常有意义并且工作正常,但是当我将存档直接部署到手机中时,它们就崩溃了。
P.S: I've also tried all the answers from this question but despite of making perfect sense and working when debugging the app, they crashed when I deployed the archive directly into the phone.
这篇关于当对象不存在时,ABRecordCopyValue不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!