IOS中擷取本地通訊錄連絡人以及漢字首字母排序_IOS

來源:互聯網
上載者:User

iOS中擷取手機通訊錄中的連絡人資訊:

/*** 載入本地連絡人*/ - (void)loadLocalContacts {   //建立一個通訊錄類   ABAddressBookRef addressBooks = nil;      if (DeviceVersion < 6.0) {     addressBooks = ABAddressBookCreate();   } else {     addressBooks = ABAddressBookCreateWithOptions(NULL, NULL);     //擷取通訊錄許可權     dispatch_semaphore_t sema = dispatch_semaphore_create(0);     ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error){dispatch_semaphore_signal(sema);});     dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);     dispatch_release(sema);   }      //判斷授權狀態   if (ABAddressBookGetAuthorizationStatus()!=kABAuthorizationStatusAuthorized) {     return ;   }      //擷取通訊錄中的所有人   CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);   //通訊錄中人數   CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);   NSMutableArray *persons = [[NSMutableArray alloc] init];   for (int i = 0; i < nPeople; i++) {     //擷取個人     ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);     //擷取個人名字     NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);     NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);     NSMutableString *name = [[NSMutableString alloc] init];     if (firstName == nil && lastName == nil) {       NSLog(@"名字不存在的情況");       name = nil;     }     if (lastName) {       [name appendString:lastName];     }     if (firstName) {       [name appendString:firstName];     }          ABMultiValueRef tmlphone = ABRecordCopyValue(person, kABPersonPhoneProperty);     NSString *telphone = (NSString *)ABMultiValueCopyValueAtIndex(tmlphone, 0);     if (telphone != nil) {       telphone = [telphone stringByReplacingOccurrencesOfString:@"-" withString:@""];       NSString *title = [NSString stringWithFormat:@"%@(%@)",name,telphone];       [persons addObject:title];     }   }      //對連絡人進行分組和排序   UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];   NSInteger highSection = [[theCollation sectionTitles] count]; //中文環境下返回的應該是27,是a-z和#,其他語言則不同      //_indexArray 是右側索引的數組,也是secitonHeader的標題   _indexArray = [[NSMutableArray alloc] initWithArray:[theCollation sectionTitles]];      NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:highSection];   //初始化27個空數組加入newSectionsArray   for (NSInteger index = 0; index < highSection; index++) {     NSMutableArray *array = [[NSMutableArray alloc] init];     [newSectionsArray addObject:array];     [array release];   }      for (NSString *p in persons) {     //擷取name屬性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就為11     NSInteger sectionNumber = [theCollation sectionForObject:p collationStringSelector:@selector(getFirstLetter)];     //把name為“林丹”的p加入newSectionsArray中的第11個數組中去     NSMutableArray *sectionNames = newSectionsArray[sectionNumber];     [sectionNames addObject:p];   }      for (int i = 0; i < newSectionsArray.count; i++) {     NSMutableArray *sectionNames = newSectionsArray[i];     if (sectionNames.count == 0) {       [newSectionsArray removeObjectAtIndex:i];       [_indexArray removeObjectAtIndex:i];       i--;     }   }      //_contacts 是連絡人數組(確切的說是二維數組)   self.contacts = newSectionsArray;   [newSectionsArray release];      [self.tableView reloadData]; } 

順便把索引和tableView dataSource的代理方法也貼一下:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {   return self.contacts.count; }  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {   return [self.contacts[section] count]; }  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {   static NSString *identifier = @"contactCell";   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];   if (cell == nil) {     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];   }      cell.imageView.image = [UIImage imageNamed:@"default_head"];   cell.textLabel.text = [self.contacts objectAtIndex:indexPath.section][indexPath.row];   return cell; }  - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {   return [_indexArray objectAtIndex:section]; }  - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {   return _indexArray; }  //索引列點擊事件 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {   return index; } 

還有兩個很重要的方法:

下面這個方法是[theCollation sectionForObject:p collationStringSelector:@selector(getFirstLetter)]; 是這裡的p對象要實現的方法,我這裡的p是NSString,你也可以用其他對象例如Person。

 NSString *ret = @"";   if (![self canBeConvertedToEncoding: NSASCIIStringEncoding]) {//如果是英語     if ([[self letters] length]>2) {       ret = [[self letters] substringToIndex:1];     }   }   else {     ret = [NSString stringWithFormat:@"%c",[self characterAtIndex:0]];   }   return ret; } 

下面這個方法是NSString得類別方法

- (NSString *)letters{   NSMutableString *letterString = [NSMutableString string];   int len = [self length];   for (int i = 0;i < len;i++)   {     NSString *oneChar = [[self substringFromIndex:i] substringToIndex:1];     if (![oneChar canBeConvertedToEncoding:NSASCIIStringEncoding]) {       NSArray *temA = makePinYin2([oneChar characterAtIndex:0]);       if ([temA count]>0) {         oneChar = [temA objectAtIndex:0];       }     }     [letterString appendString:oneChar];   }   return letterString; } 

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.