我在我正在处理的应用程序中有几次调用ABAddressBookCreate()。对于iOS> = 6兼容性,我想使用单例来检查对地址簿的访问并从单例中返回ABAddressBookRef。但是我不确定如何正确释放ABAddressBookRef实例或者这种方法是否可以安全使用。
+(ABAddressBookRef)loadContacts {
ABAddressBookRef ref;
if ([self isABAddressBookCreateWithOptionsAvailable]) {
CFErrorRef error = nil;
ref = ABAddressBookCreateWithOptions(NULL,&error);
ABAddressBookRequestAccessWithCompletion(ref, ^(bool granted, CFErrorRef error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
[self showErrorDialog:@"Error"];
} else if (!granted) {
[self showErrorDialog:@"Not granted"];
}
});
});
// [(id)ref autorelease]; not working..
return ref;
} else {
// iOS 4/5
ref = ABAddressBookCreate();
// [(id)ref autorelease];
return ref;
}
}
在ViewController中调用:
ABAddressBookRef addressBook = [AddressBookAccess loadContacts];