Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

ios - Swift - Checking unmanaged address book single value property for nil

I'm relative new to iOS-Development and swift. But up to this point I was always able to help myself by some research on stackoverflow and several documentations and tutorials. However, there is a problem I couldn't find any solution yet.

I want to get some data from the users addressbook (for example the single value property kABPersonFirstNameProperty). Because the .takeRetainedValue() function throws an error if this contact doesn't have a firstName value in the addressbook, I need to make sure the ABRecordCopyValue() function does return a value. I tried to check this in a closure:

let contactFirstName: String = {
   if (ABRecordCopyValue(self.contactReference, kABPersonFirstNameProperty) != nil) {
      return ABRecordCopyValue(self.contactReference, kABPersonFirstNameProperty).takeRetainedValue() as String
   } else {
      return ""
   }
}()

contactReference is a variable of type ABRecordRef!

When an addressbook contact provides a firstName value, everything works fine. But if there is no firstName, the application crashes by the .takeRetainedValue() function. It seems, that the if statement doesn't help because the unmanaged return value of the ABRecordCopyValue() function is not nil although there is no firstName.

I hope I was able to make my problem clear. It would be great if anyone could help me out with some brainwave.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I want the values associated with various properties, I use the following syntax:

let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String
let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String

Or you can use optional binding:

if let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
    // use `first` here
}
if let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String {
    // use `last` here
}

If you really want to return a non-optional, where missing value is a zero length string, you can use the ?? operator:

let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String ?? ""
let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String ?? ""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...