从地址簿获取信息时出错

时间:2012-09-27 04:06:55

标签: ios objective-c iphone cocoa

我在从地址簿中检索某些数据的数组时遇到问题。这是代码:

- (void) getContacts{    
    ABAddressBookRef ab = ABAddressBookCreate();
    NSMutableArray *retVal = (__bridge NSMutableArray *)(ABAddressBookCopyArrayOfAllPeople(ab));
    CFRelease(ab);

    contact* temp=[[contact alloc] init];
    NSMutableArray* tempArray=[[NSMutableArray alloc]init];

    for(int i=0;i<[retVal count];i++)
        [tempArray insertObject:
          [NSString stringWithFormat:@"%@",
            [temp set2:[NSString stringWithFormat:@"%@",
              [[retVal objectAtIndex:i] kABPersonFirstNameProperty]] 
                  last:[NSString stringWithFormat:@"%@",
                    [[retVal objectAtIndex:i] kABPersonLastNameProperty]] 
                number:[NSString stringWithFormat:@"%@",
                  [[retVal objectAtIndex:i] kABPersonPhoneProperty]]]] atIndex:i];

    _objects=tempArray;

    [self alert:[NSString stringWithFormat:@"%@",_objects] title:@"TEMP"];
}

我得到的错误与kABPerson属性有关。

更多澄清一下:基本上我将地址簿中的所有数据都抓到第一个数组中,然后我手动浏览该数组并尝试检索我应用程序其余部分所需的数据。 / p>

有什么想法吗?

Just for more clarification here's my contact.h file:

@interface contact : NSString{
    NSString* first;
    NSString* last;
    NSString* number;
}
@end

这是我的contact.m文件:

@implementation contact

- (void) set:(NSString*)first2 last:(NSString*)last2 number:(NSString*)number2{
    first=first2;
    last=last2;
    number=number2;
}

- (contact*) set2:(NSString*)first2 last:(NSString*)last2 number:(NSString*)number2{
    first=first2;
    last=last2;
    number=number2;

    return self;
}

@end

这条线似乎太长了,无法发布:

//Enter contact into tempArray
    [tempArray insertObject:[NSString stringWithFormat:@"%@",[temp set:[NSString stringWithFormat:@"%@",(__bridge NSString *)(ABRecordCopyValue((__bridge ABMultiValueRef)[retVal objectAtIndex:i],kABPersonFirstNameProperty))] last:[NSString stringWithFormat:@"%@",(__bridge NSString *)(ABRecordCopyValue((__bridge ABMultiValueRef)[retVal objectAtIndex:i],kABPersonLastNameProperty))] number:(__bridge NSString *)ABMultiValueCopyValueAtIndex((__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)([retVal objectAtIndex:i]),kABPersonPhoneProperty)), 0)]] atIndex:i];

1 个答案:

答案 0 :(得分:0)

kABPersonFirstNameProperty是属性 ID ,而不是Objective-C对象属性。

也就是说,你不能使用[[retVal objectAtIndex:i] kABPersonFirstNameProperty] - 你需要像这样访问名字和姓氏:

CFStringRef firstName = ABRecordCopyValue ([retVal objectAtIndex:i], kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue ([retVal objectAtIndex:i], kABPersonLastNameProperty);
CFStringRef phoneNum = ABRecordCopyValue ([retVal objectAtIndex:i], kABPersonPhoneProperty);

然后不要忘记ABRecordCopyValue遵循创建规则 - 之后你需要CFRelease(firstName)