如果联系人的名字或姓氏为空白,则该值为nil
还是""
?
答案 0 :(得分:2)
从Xcode 6 Beta 4开始,该值为nil
。
要亲眼看看,请运行以下代码两次:
// AppDelegate.swift
import AddressBookUI
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var error: Unmanaged<CFError>?
let addressBookTemp = ABAddressBookCreateWithOptions(nil, &error)
if !addressBookTemp {
println(error)
return true
}
let addressBook = Unmanaged<NSObject>.fromOpaque(addressBookTemp.toOpaque()).takeRetainedValue()
ABAddressBookRequestAccessWithCompletion(addressBook, nil)
var allPeople: NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
println("allPeople.count: \(allPeople.count)")
for person in allPeople {
let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)
let firstName: NSObject! = Unmanaged<NSObject>.fromOpaque(firstNameTemp.toOpaque()).takeRetainedValue()
if firstName {
println("firstName: \(firstName)")
} else {
println("fristName is nil")
}
let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)
let lastName: NSObject! = Unmanaged<NSObject>.fromOpaque(lastNameTemp.toOpaque()).takeRetainedValue()
if lastName {
println("lastName: \(lastName)")
} else {
println("lastName is nil")
}
}
return true
}
}
答案 1 :(得分:2)
如果某人没有姓或名,则该值为nil
。
如果要将其强制转换为空字符串,可以执行以下操作:
// Getting the first and the last name of person
let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)?;
let firstName: NSObject? = Unmanaged<NSObject>.fromOpaque(firstNameTemp!.toOpaque()).takeRetainedValue();
var first_name = "";
if firstName != nil {
first_name = firstName! as NSString;
}
let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)?;
let lastName: NSObject? = Unmanaged<NSObject>.fromOpaque(lastNameTemp!.toOpaque()).takeRetainedValue();
var last_name = "";
if lastName != nil {
last_name = lastName! as NSString;
}