gpt4 book ai didi

ios - 访问 ABAddressBook 时出错

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:26 29 4
gpt4 key购买 nike

我正在使用以下代码访问 ABAddressBook:

+ (void)connectToAddressBook {
if(!_addressBook)
{
CFErrorRef error;
_addressBook = ABAddressBookCreateWithOptions(NULL, &error);
NSLog(@"Address book %@", _addressBook);

if (error != nil) {
NSLog(@"ERROR WHILE ACCESSING ADDRESS BOOK: %@", CFBridgingRelease(error));
CFRelease(error);
}

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {
_isAccessToContactsAllowed = granted;
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
_isAccessToContactsAllowed = YES;
}
else {
_isAccessToContactsAllowed = NO;
}
}
}

地址簿打开正常,但由于某种原因错误不是零并记录当前类(class)的名称:

ERROR WHILE ACCESSING ADDRESS BOOK: MyContactManager

为什么错误不是零?我的代码有什么问题吗?如果出现真正的错误,我如何检测并停止尝试访问地址簿?

最佳答案

由于 Ilesh 的反馈,这是我的固定方法:

+ (void)connectToAddressBook {
if(!_addressBook) {
CFErrorRef *error = nil;
_addressBook = ABAddressBookCreateWithOptions(NULL, error);

// To test if error is not nil:
//error = CFErrorCreate(NULL, CFSTR("Hello, world."), 111, NULL);

if (error != nil) {
NSLog(@"ERROR WHILE ACCESSING ADDRESS BOOK: %@", CFBridgingRelease(error));
CFRelease(error);
}
else {
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {
_isAccessToContactsAllowed = granted;
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
_isAccessToContactsAllowed = YES;
}
else {
_isAccessToContactsAllowed = NO;
}
}
}
}

编辑:

看来我最初的错误是没有将错误分配给 nil。地址簿创建不会设置错误除非确实存在错误。所以我未分配的变量指向内存中的某个随机位置,这就是我第一次尝试时出现随机错误的原因。

此外,ABAddressBookCreateWithOptions 会在出现错误时返回nil,因此正确的做法是:

if(_addressBook) {
// do something
}
else {
// there is an error
}

关于ios - 访问 ABAddressBook 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200787/

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