ABRecordCopyValue not working when object doesn't exist
Asked Answered
Q

1

3

This line of code in Swift causes me problems when the address book has a contact with no last name.

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

let lName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as String
Quaker answered 19/11, 2014 at 6:14 Comment(0)
C
3

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")
}

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)")
}

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.

Coheman answered 29/1, 2015 at 23:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.