2012-07-13 24 views
1

通過使用initWithVCardRepresentation:方法,AddressBook Framework爲使用vCard初始化ABPerson提供了一個很好的方法。如何(輕鬆地)用vCard更新ABPerson對象並保持其唯一ID?

我想要做的是更新與某個vCard的聯繫。我不能使用initWithVCardRepresentation:,因爲這會給我一個新的ABPerson對象和一個新的uniqueId,我想保持這些更改之間的uniqueId。

什麼是這樣做的簡單方法嗎?

謝謝!

回答

3

initWithVCardRepresentation仍然是將您的電子名片變成ABPerson的最明智的方式。

只需使用它的結果在您的地址簿中找到匹配的人員,然後遍歷vCard屬性,將它們放入現有記錄中。最後的保存會加強你的改變。

以下示例假定唯一的「密鑰」爲last-namefirst-name。如果您想要包含沒有列出名稱的公司或者其他任何公司,您可以修改搜索元素,或者您可以通過獲取[AddressBook people]來更改迭代方案,然後迭代人員並僅使用鍵值對符合您的滿意度。

- (void)initOrUpdateVCardData:(NSData*)newVCardData { 
    ABPerson* newVCard = [[ABPerson alloc] initWithVCardRepresentation:newVCardData]; 
    ABSearchEleemnt* lastNameSearchElement 
     = [ABPerson searchElementForProperty:kABLastNameProperty 
            label:nil 
             key:nil 
            value:[newVCard valueForProperty:kABLastNameProperty] 
           comparison:kABEqualCaseInsensitive]; 
    ABSearchEleemnt* firstNameSearchElement 
     = [ABPerson searchElementForProperty:kABFirstNameProperty 
            label:nil 
             key:nil 
            value:[newVCard valueForProperty:kABFirstNameProperty] 
           comparison:kABEqualCaseInsensitive]; 
    NSArray* searchElements 
     = [NSArray arrayWithObjects:lastNameSearchElement, firstNameSearchElement, nil]; 
    ABSearchElement* searchCriteria 
     = [ABSearchElement searchElementForConjunction:kABSearchAnd children:searchElements]; 
    AddressBook* myAddressBook = [AddressBook sharedAddressBook]; 
    NSArray* matchingPersons = [myAddressBook recordsMatchingSearchElement:searchCriteria]; 
    if (matchingPersons.count == 0) 
    { 
     [myAddressBook addRecord:newVCard]; 
    } 
    else if (matchingPersons.count > 1) 
    { 
     // decide how to handle error yourself here: return, or resolve conflict, or whatever 
    } 
    else 
    { 
     ABRecord* existingPerson = matchingPersons.lastObject; 
     for (NSString* property in [ABPerson properties]) // i.e. *all* potential properties 
     { 
      // if the property doesn't exist in the address book, value will be nil 
      id value = [newVCard valueForProperty:property]; 
      if (value) 
      { 
       NSError* error; 
       if (![existingPerson setValue:value forProperty:property error:&error] || error) 
        // handle error 
      } 
     } 
     // newVCard with it's new unique-id will now be thrown away 
    } 
    [myAddressBook save]; 
} 
相關問題