当我试图联系一个电话号码时,我收到错误“致命错误:在展开可选值时意外发现nil”

时间:2016-05-10 08:09:21

标签: ios

if let phone:ABMultiValueRef = ABRecordCopyValue(con,kABPersonPhoneProperty).takeRetainedValue()
   {
        for (var k = 0 ; k < ABMultiValueGetCount(phone) ; ++k){
            //获取电话Label
            var personPhoneLabel:String   = ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k).takeRetainedValue()).takeRetainedValue()as String
            //获取該Label下的电话值
            var personPhone:String = ABMultiValueCopyValueAtIndex(phone, k).takeRetainedValue() as! String
            phoneNum = personPhone
            print(personPhoneLabel+":"+personPhone)
        }
    }
    else{
        phoneNum = ""
    }

错误行是第一行:

 if let phone:ABMultiValueRef = ABRecordCopyValue(con, kABPersonPhoneProperty).takeRetainedValue() 

为什么“if let”不起作用?

2 个答案:

答案 0 :(得分:1)

ABRecordCopyValue可以返回nil,因此您需要在对返回值调用takeRetainedValue()之前进行检查

编辑 - 执行类似

的操作
let copiedValue = ABRecordCopyValue(con,kABPersonPhoneProperty)
if let phone = copiedValue?.takeRetainedValue() {
....

答案 1 :(得分:0)

我已经解决了我的问题。正确的代码如:

if let unmanagedPhone = ABRecordCopyValue(con, kABPersonPhoneProperty){
        var phone:ABMultiValueRef = unmanagedPhone.takeUnretainedValue()

        if let unmanagedPhoneNumberArray = ABMultiValueCopyArrayOfAllValues(phone){
            var phoneNumberArray = unmanagedPhoneNumberArray.takeUnretainedValue() as NSArray
            phoneNum = phoneNumberArray[0] as! String
        }
    }
    else{
        phoneNum = ""
    }