从ABPeoplePickerNavigationController获取人员时缺少数据

时间:2012-10-15 19:17:55

标签: iphone objective-c ios abaddressbook

我有一个奇怪的AddressBook框架行为。 我正在以这种方式创建和显示人员选择器控制器:

ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonFirstNameProperty], [NSNumber numberWithInt:kABPersonLastNameProperty], nil];
picker.displayedProperties = displayedItems;
[self presentViewController: picker animated:YES completion: nil];

然后在代表中我有以下内容:

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    myPersonRec = person;
    [self dismissViewControllerAnimated:YES completion: nil];
    return NO;
}

稍后当我尝试访问myPersonRec属性时,我只能读取名字和姓氏(显示在人员选择器中),所有其他属性都是零。如果我将返回值更改为YES,我会收到电话号码和所有内容,但无论如何都无法获取此人的图片。我做错了什么?

1 个答案:

答案 0 :(得分:0)

发现了问题来源:

ABPerson对象不会立即加载到内存中。它是部分加载的,并且在需要时加载新的字段或图像,并且为了正确加载,该对象应该绑定到现有的ABAddressBook实例。当我使用person picker viewcontroller时,它引用了它自己的ABAddressBook实例,该实例在picker被解除后被释放,所以在viewcontroller解雇后我无法获得任何新数据(但之前加载的条目仍可访问) )。

为了解决这个问题,我在我的模型类单例中创建了一个ABAddressBook共享实例,并在需要时使用它。由于我只是在阅读地址簿,所以应该是很好的解决方案。

因此,创建代码的选择器应该最终看起来像这样:

ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonFirstNameProperty], [NSNumber numberWithInt:kABPersonLastNameProperty], nil];
picker.displayedProperties = displayedItems;
picker.addressBook = [[MyModel instance] sharedAddressBookRef];
[self presentViewController: picker animated:YES completion: nil];