6

我想获取用户的邮件地址,如这个线程所示:Getting user's default email address in Cocoa

但是当我尝试时:

NSString *theEmailAddressWeWantToObtain = @"";
ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me];
ABMultiValue *emails = [aPerson valueForProperty:kABEmailProperty];
if([emails count] > 0)
        theEmailAddressWeWantToObtain = [emails valueAtIndex:0];

我有这些错误:

  • 使用未声明的标识符“aPerson”
  • 使用未声明的标识符“ABAddressBook”
  • 未知类型“ABMultiValue”

我已经链接了 AddressBook 和 AddressBookUI,并导入了 AddressBook/AddressBook.h

怎么了 ?

4

1 回答 1

7

这些是对您的代码的更正

NSString *theEmailAddressWeWantToObtain = @"";
ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me];
ABMultiValueRef *emails = [aPerson valueForProperty:kABEmailProperty]; //No such thing as ABMultiValue; it's ABMultiValueRef
if(ABMultiValueGetCount(emails) > 0) //"emails" is not an array, so you can't use the "count" method
    theEmailAddressWeWantToObtain = [emails valueAtIndex:0];

我对键值编码不太熟悉,所以我不确定你的方法与此相关。

这是我会做的方式

电子邮件中存储了三个电子邮件地址ABMultiValueRef:家庭、工作和其他电子邮件。试试这个代码来获取家庭电子邮件:

NSString *email;

ABRecordRef currentPerson = (__bridge ABRecordRef)[[PSAddressBook arrayOfContacts] objectAtIndex:identifier];
ABMultiValueRef emailsMultiValueRef = ABRecordCopyValue(currentPerson, kABPersonEmailProperty);

NSUInteger emailsCount;    
//Goes through the emails to check which one is the home email
for(emailsCount = 0; emailsCount <= ABMultiValueGetCount(emailsMultiValueRef);emailsCount++){ 
    NSString *emailLabel = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex (emailsMultiValueRef, emailsCount);

    if([emailLabel isEqualToString:@"Home"]){

        if ((__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emailsMultiValueRef, emailsCount) != NULL){

            email = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonEmailProperty);
        }   

        //If the last name property does not exist
        else{

            email = @"NULL";
        }
    }
}

CFRelease(emailsMultiValueRef);

如果您对代码有任何疑问,请在评论中提问。希望这可以帮助!

编辑:

代码中提到的PSAddressBook类可以在这里找到:https ://github.com/pasawaya/PSAddressBook

于 2012-06-27T16:20:02.097 回答