I have tableview and inside there i have address book items (firstName, lastName, phone) So i have cell which shows only the last property from my device multiplied on numberOfRowsInSection
but after that i have println()
and it gives me the whole list of contact names. I could not understand why is this all happening please help me. To Recap: In Xcode I Have Whole List Of Contacts But On The Device i Have Only The Last One And 5 times.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
let allPeople = ABAddressBookCopyArrayOfAllPeople(AddressBookForVC).takeRetainedValue() as NSArray
for person: ABRecordRef in allPeople{
let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""
let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""
let phones: ABMultiValueRef = ABRecordCopyValue(person,kABPersonPhoneProperty).takeRetainedValue()
let countOfPhones = ABMultiValueGetCount(phones)
for index in 0..<countOfPhones{
let phone = ABMultiValueCopyValueAtIndex(phones, index).takeRetainedValue() as! String
// println("\(firstName) \(lastName) \(phone)")
cell.textLabel?.text = firstName
println(firstName)
}
}
// cell.textLabel?.text = swiftBlogs[row]
return cell
}
The cellForRowAtIndexPath
is called once for every row in the table. And each time you're calling cellForRowAtIndexPath
, you're extracting and iterating though the array of all contacts each time.
The code for copying/looping all of the contacts doesn't make sense inside cellForRowAtIndexPath
. Usually you'd extract all of that information earlier (e.g. in viewDidLoad
), and populate an array once. Then cellForRowAtIndexPath
would simply look up data in that array, not going back to the address book and re-extracting all of the contacts every time.