gpt4 book ai didi

ios - 从 ABAddressBookRequestAccessWithCompletion() 获取联系人数组给出 nil

转载 作者:行者123 更新时间:2023-11-28 19:05:09 25 4
gpt4 key购买 nike

我正在尝试使用 NSLog() 将我手机的所有联系人打印到控制台。目前这段代码只是打印(null)

.h

@property (nonatomic, strong) NSMutableArray *contactsObjects;

.m

@synthesize contactsObjects;
//lazy instantiation.
- (NSMutableArray *)contactsObjects
{
if(!contactsObjects)
{
contactsObjects = [[NSMutableArray alloc]init];
}

return contactsObjects;
}

- (void)viewWillAppear:(BOOL)animated
{
CFErrorRef error = nil;

// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, &error);

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
// First time access has been granted, add all the user's contacts to array.
CFMutableArrayRef contactsObjects = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
} else {
// User denied access.
// Display an alert telling user that they must allow access to proceed to the "invites" page.
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add all the user's contacts to array.
CFMutableArrayRef contactsObjects = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
}
else {
// The user has previously denied access
// Send an alert telling user that they must allow access to proceed to the "invites" page.
}

NSLog(@"%@", contactsObjects);
}

我在这里收到两个警告:

enter image description here

我不知道应该怎么做才能将联系人的姓名和号码正确地打印到控制台。

如何打印我的联系人姓名和电话号码?

最佳答案

您的代码存在范围问题。 viewWillAppear: 中的 contactsObjects 变量与您称为 contactsObjects 的 ivar 无关。您正在声明使用相同名称的新变量。另一方面,末尾的 NSLog() 是 ivar。但是设置那些其他变量并没有将任何东西放入 ivar,所以你看到 (null),这就是 NSLog() 表示“无对象”的方式。

通过不创建新的变量声明,而是使用 ivar 来解决这个问题。

if (granted) {
contactsObjects = ABAddressBookCopyArrayOfAllPeople(addressBookRef);

else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
contactsObjects = ABAddressBookCopyArrayOfAllPeople(addressBookRef);

您还需要转换这些:

    contactsObjects = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBookRef);

(此外,该函数不返回可变数组,因此您可能会遇到麻烦。)

第二个问题是 ABAddressBookRequestAccessWithCompletion() 不会停止并等待其完成 block 运行。在请求访问时,您的方法的其余部分将继续进行,因此在实际设置 contactsObjects 之前,您会到达 NSLog()

关于ios - 从 ABAddressBookRequestAccessWithCompletion() 获取联系人数组给出 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21082907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com