我有一个类在 iPhone 应用程序中保存我的用户的联系人列表。
其核心实现如下。
//file Contacts.m
//imports here
void MyAddressBookExternalChangeCallback (
ABAddressBookRef addressBook,
CFDictionaryRef info,
void *context
)
{
NSLog(@"callback called ");
[[Contacts sharedInstance] refresh];
}
@implementation Contacts
@synthesize addressBook;
+ (Contacts*)sharedInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
{
sharedInstance = [[Contacts alloc] init];
}
}
return sharedInstance;
}
- (void)refresh
{
ABAddressBookRevert(addressBook); /*refreshing the address book in case of changes*/
[people release];
people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
}
- (id)init
{
if ((self = [super init]))
{
sharedInstance = self;
addressBook = ABAddressBookCreate();;
people = nil;
[self refresh];
ABAddressBookRegisterExternalChangeCallback ( addressBook,
MyAddressBookExternalChangeCallback,
self
);
}
return sharedInstance;
}
在 init
中,我设置了一个外部回调 MyAddressBookExternalChangeCallback
来通知联系人列表的更改。
我遇到的问题是,当我在 iPhone 手机应用程序中添加联系人时,不会调用外部回调(我从未看到 nslog 消息的结果)。
我做错了什么?
添加注释:如果我这样做,甚至更陌生
ABAddressBookRevert(addressBook);
每次我的应用程序出现在前面并且通讯录被修改时,回调就会被调用。
最佳答案
我在我的 iPhone 上测试了这个并验证回调被调用:
联系人.h:
#import <Foundation/Foundation.h>
#import <AddressBook/AddressBook.h>
@interface Contacts : NSObject
{
ABAddressBookRef addressBook;
NSArray *people;
}
+ (Contacts*)sharedInstance;
- (void)refresh;
void MyAddressBookExternalChangeCallback (
ABAddressBookRef addressBook,
CFDictionaryRef info,
void *context
);
@end
联系人.m:
#import "Contacts.h"
void MyAddressBookExternalChangeCallback (
ABAddressBookRef addressBook,
CFDictionaryRef info,
void *context
)
{
NSLog(@"callback called ");
[[Contacts sharedInstance] refresh];
}
@implementation Contacts
+ (Contacts*)sharedInstance
{
static Contacts *sharedInstance = nil;
@synchronized(self)
{
if (sharedInstance == nil)
{
sharedInstance = [[Contacts alloc] init];
}
}
return sharedInstance;
}
- (void)refresh
{
ABAddressBookRevert(addressBook); /*refreshing the address book in case of changes*/
[people release];
people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
}
- (id)init
{
if ((self = [super init]))
{
//sharedInstance = self;
addressBook = ABAddressBookCreate();
people = nil;
[self refresh];
ABAddressBookRegisterExternalChangeCallback (addressBook,
MyAddressBookExternalChangeCallback,
self
);
}
return self;
}
@end
关于objective-c - iOS 中未调用 ABAddressBook 外部回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9112671/