2015-05-19 203 views
1

CFArraySortValues在Objective-C聯繫人排序,如下我樣的人的數組。以下:與斯威夫特

let ctx = UnsafeMutablePointer<Void>.alloc(kABPersonSortByFirstName) 

CFArraySortValues(mutablePeople, 
        CFRangeMake(0, CFArrayGetCount(mutablePeople)), 
        ABPersonComparePeopleByName, 
        ctx) 

給出編譯錯誤:

Cannot invoke 'CFArraySortValues' with an argument list of type '(CFMutableArray!, CFRange, (ABRecord!, ABRecord!, ABPersonSortOrdering) -> CFComparisonResult, UnsafeMutablePointer)'

的問題看起來是與將在Objective-C被轉換爲CFComparatorFunctionABPersonComparePeopleByName

回答

5

這裏有兩個備選方案是避免CFArraySortValues乾脆:

  1. 使用ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering檢索已排序聯繫人:

    let people = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, nil, ABPersonSortOrdering(kABPersonSortByFirstName)).takeRetainedValue() as [ABRecordRef] 
    

    如果使用nil爲源,它使用各種來源(雖然該行爲沒有記錄)。

  2. 或者,如果你有ABRecordRef迅捷的數組,然後你可以使用標準的斯威夫特排序例程,使用ABPersonComparePeopleByName的比較:

    var people = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as [ABRecordRef] 
    people.sort() { ABPersonComparePeopleByName($0, $1, ABPersonSortOrdering(kABPersonSortByFirstName)) != .CompareGreaterThan } 
    

這兩種方法返回一個斯威夫特Array<ABRecordRef> ,這是一個很好的本地Swift集合。例如,要打印名稱列表:

for record in people { 
    let name = ABRecordCopyCompositeName(record).takeRetainedValue() 
    println(name) 
} 
+0

兩個很好的答案,正是我所需要的,謝謝。 –