tableView cellForRowAtIndexPath稍后调用

时间:2015-04-02 07:22:08

标签: ios objective-c ios8 tableview

我正在从设备获取联系人并在tableview中显示 但第一次在联系人屏幕上显示联系人权限,当我点击okey tableview numberofrow被叫,但是5秒后调用了cellForRowAtIndexPath 我正在使用此代码(此问题仅在新应用安装时第一次出现) 我在xib和.h文件中添加了委托和数据源

-(void)getContactsFromAddressBook
{

addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
    ABAddressBookRequestAccessWithCompletion(addressBook,
                                             ^(bool granted, CFErrorRef error) {
                                                 if (granted)
                                                     [self loadContacts];
                                             });
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
    [self loadContacts];
}
else {
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:Nil message:@"You don't have permission of access contacts for access go to Setting-> Doubls-> Contacts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
} 

//加载联系人

-(void)loadContacts
{
[arr_Contact removeAllObjects];
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
//arr_Contact = (__bridge NSMutableArray*)allPeople;
for(int i = 0; i < numberOfPeople; i++) {

    ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );

    NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
    //NSLog(@"Name:%@ %@", firstName, lastName);

    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

    NSString *phoneNumber;
    for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
        phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
       // NSLog(@"phone:%@", phoneNumber);
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    if(firstName == nil)
    {
        firstName = @"";
    }
    if(lastName == nil)
    {
        lastName = @"";
    }
    if(phoneNumber == nil)
    {
        continue;
    }
    [dic setValue:[NSString stringWithFormat:@"%@ %@",firstName,lastName] forKey:@"firstName"];
    //[dic setValue:lastName forKey:@"lastName"];
    [dic setValue:phoneNumber forKey:@"phonesNum"];


    [arr_Contact addObject:dic];

}
NSLog(@"arr all contact %@",arr_Contact);


NSSortDescriptor *sorter = [[NSSortDescriptor alloc]
                            initWithKey:@"firstName"
                            ascending:YES
                            selector:@selector(compare:)] ;
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[arr_Contact sortUsingDescriptors:sortDescriptors];

[arr_afterSearch addObjectsFromArray:arr_Contact];

[self createSectionList:arr_Contact];

}

//创建部分

- (void) createSectionList: (id) wordArray
{
for (int i = 0; i < 27; i++) [arr_searchContact addObject:[[NSMutableArray alloc] init]];
int k=0;
NSLog(@"arr count is %lu",(unsigned long)[arr_Contact count]);
for (k=0; k<[arr_Contact count]; k++) {

    NSString *word = [NSString stringWithFormat:@"%@",[[arr_Contact valueForKey:@"firstName"]objectAtIndex:k]];

    if ([word length] == 0) continue;
    @try {
        range1 = [ALPHA rangeOfString:[[word substringToIndex:1] uppercaseString]];
        [[arr_searchContact objectAtIndex:range1.location]addObject:[arr_Contact objectAtIndex:k]];
    }
    @catch (NSException * e) {
        [[arr_searchContact objectAtIndex:26]addObject:[arr_Contact objectAtIndex:k]];
        NSLog(@"error");
    }
    @finally {
    }
}
[self.tblContact reloadData];
}

// tableview委托

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows=0;

if (IsSearching==TRUE) {
    rows=[arr_afterSearch count];
}
else{
     rows=[[arr_searchContact objectAtIndex:section] count];
}



return rows;
}
 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 return 40;
 }
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger section=0;

if (IsSearching==TRUE) {
    section=1;
}
else{
    if ([arr_searchContact count]>0) {
        section=[ALPHA_ARRAY count];
    }
    else{
        section=0;
    }
}

return section;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
if (IsSearching==TRUE) {
    return nil;
}
else{
    return ALPHA_ARRAY;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:   (NSInteger)section
{
// create the parent view that will hold header Label

if (IsSearching==TRUE) {
    return nil;
}
else{

if([[arr_searchContact objectAtIndex:section] count]==0)
{
    return nil;
}
else {
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(5.0, 0.0, 320.0, 25.0)];
    [customView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:239.0/255.0 blue:240.0/255.0 alpha:1.0]];
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.font = [UIFont systemFontOfSize:14];
    headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 24.0);
    [headerLabel setText:[NSString stringWithFormat:@"%@",[ALPHA_ARRAY objectAtIndex:section]]];
     [headerLabel setTextColor:[UIColor lightGrayColor]];
    [customView addSubview:headerLabel];

    return customView;
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (IsSearching==TRUE) {
    return 0;
}
else{
    if([[arr_searchContact objectAtIndex:section] count]==0)
    {
        return 0;
    }
    else
    {
        return 25;
    }
}
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    cell.backgroundColor=[UIColor clearColor];
    cell.accessoryType = UITableViewCellAccessoryNone;

    UIView *selectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 46)];
    [selectionView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:82.0/255.0 blue:91.0/255.0 alpha:1.0]];
    cell.selectedBackgroundView = selectionView;

    if ([tableView respondsToSelector:@selector(setSectionIndexColor:)]) {
        tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:0.3];
        tableView.sectionIndexTrackingBackgroundColor = [UIColor whiteColor];
    }
}
NSMutableDictionary *dic = [arr_Contact objectAtIndex:indexPath.row];
//cell.textLabel.text = [dic objectForKey:@"firstName"];
//cell.lastNameLabel.text = [dic objectForKey:@"lastName"];
 if (IsSearching==TRUE) {
     NSDictionary *dic=[arr_afterSearch objectAtIndex:indexPath.row];
     if ([[dic objectForKey:@"firstName"] length]>0) {
     cell.textLabel.text = [dic objectForKey:@"firstName"];
     }
     else{
         cell.textLabel.text =[dic objectForKey:@"phonesNum"];
     }
 }
 else{
     NSDictionary *dic=[[arr_searchContact objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
     if ([[dic objectForKey:@"firstName"] length]>0) {
         cell.textLabel.text = [dic objectForKey:@"firstName"];
     }
     else{
         cell.textLabel.text =[dic objectForKey:@"phonesNum"];
     }
 }
cell.textLabel.textColor=[UIColor darkGrayColor];
cell.textLabel.highlightedTextColor = [UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:@"OpenSans" size:14.0];
return cell;

}

1 个答案:

答案 0 :(得分:1)

您需要确保仅从主队列更新UI。地址簿访问的完成处理程序将在后台线程上执行。更改完成处理程序以在主队列上调用loadContacts

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
    ABAddressBookRequestAccessWithCompletion(addressBook,
              ^(bool granted, CFErrorRef error) {
                  if (granted) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                             [self loadContacts];
                      });
                  }
               });