我尝试从地址簿中加载一些特定的联系人,并将ABRecordRef存储到一个可变的字典数组中。我正在使用ARC,这是我的方法:
- (ABRecordRef) findContactsMatchingFullName:(NSString *)contactFullName
{
ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NULL);
NSArray *allRecords = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(ab));
NSCharacterSet *space = [NSCharacterSet whitespaceCharacterSet];
NSMutableArray *contactsMutableArray = [NSMutableArray array];
NSDictionary *contact;
NSUInteger numberOfContacts = allRecords.count;
for (int i = 0; i < numberOfContacts; i++)
{
ABRecordRef record = (__bridge ABRecordRef)(allRecords[i]);
NSString *fname = ( NSString *)CFBridgingRelease(ABRecordCopyValue(record, kABPersonFirstNameProperty));
NSString *lname = ( NSString *)CFBridgingRelease(ABRecordCopyValue(record, kABPersonLastNameProperty));
NSString *mname = ( NSString *)CFBridgingRelease(ABRecordCopyValue(record, kABPersonMiddleNameProperty));
NSString *organization = ( NSString *)CFBridgingRelease(ABRecordCopyValue(record, kABPersonOrganizationProperty));
if (fname || lname || mname || organization)
{
if (!fname) fname = @"";
if (!lname) lname = @"";
if (!mname) mname = @"";
if (!organization) organization = @"";
NSString *fullName = [[[[fname stringByAppendingFormat:@" %@", mname] stringByTrimmingCharactersInSet:space] stringByAppendingFormat:@" %@", lname] stringByTrimmingCharactersInSet:space];
contact = [[NSDictionary alloc] initWithObjectsAndKeys:
(__bridge id)record, ksABRecordRef,
fullName, ksFullName,
organization, ksOrganization,
nil];
[contactsMutableArray addObject:contact];
}
}
if (ab) CFRelease(ab);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K LIKE[CD] %@ OR %K LIKE[CD] %@",
ksFullName, contactFullName, ksOrganization, contactFullName];
NSArray *filteredArray = [contactsMutableArray filteredArrayUsingPredicate:predicate];
if (filteredArray.count == 1)
return (__bridge ABRecordRef)([filteredArray[0] objectForKey:ksABRecordRef]);
else
return nil;
}
- (void)loadContacts:(NSArray*)contactNames
{
if (!_contacts)
_contacts = [[NSMutableArray alloc] init];
else
[_contacts removeAllObjects];
for (NSString* name in contactNames)
{
ABRecordRef contactRecord = [self findContactsMatchingFullName:name]; contacts
if (contactRecord)
[_contacts addObject:(__bridge id)contactRecord];
}
}
在loadContacts
方法中,每次调用findContactsMatchingFullName
内存后,内存使用量将会增加很多。大多数内存使用都发生在这一行之后:
NSArray *allRecords = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(ab));
CFBrigingRelease版本不应该保留ABAddressBookCopyArrayOfAllPeople
的数量吗?