ios - 访问 ABAddressBook 时出错
<p><p>我正在使用以下代码访问 ABAddressBook:</p>
<pre><code>+ (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;
}
}
}
</code></pre>
<p>地址簿打开正常,但由于某种原因错误不是 nil 并记录当前类的名称:</p>
<pre><code>ERROR WHILE ACCESSING ADDRESS BOOK: MyContactManager
</code></pre>
<p>为什么error不为零?我的代码有什么错误吗?在发生真正错误的情况下,如何检测并停止尝试访问地址簿?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>感谢 Ilesh 的反馈,这是我的固定方法:</p>
<pre><code>+ (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;
}
}
}
}
</code></pre>
<p><strong>编辑:</strong></p>
<p>看来我最初的错误是没有将错误分配给<em>nil</em>。通讯簿创建不会设置错误<strong>除非确实存在错误</strong>。所以我未分配的变量指向内存中的某个随机位置,这就是我第一次尝试时出现随机错误的原因。</p>
<p>更重要的是,ABAddressBookCreateWithOptions如果有错误会返回<em>nil</em>,所以正确的做法是:</p>
<pre><code>if(_addressBook) {
// do something
}
else {
// there is an error
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 访问 ABAddressBook 时出错,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/31200787/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/31200787/
</a>
</p>
页:
[1]