Objective-C: Memory issue when import large amount of contacts from NSData

250 Views Asked by At

I'm trying to import contacts from NSData object in ARC using the code below:

- (void) importAllVcard: (NSData *)VcardData
{
    NSString *vCardString = [[NSString alloc] initWithData:VcardData encoding:NSUTF8StringEncoding];
    CFDataRef vCardData = (__bridge CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding];

    ABAddressBookRef book = ABAddressBookCreate();
    ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book);
    CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);

    NSArray *array = (__bridge NSArray*)vCardPeople;
    for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
        @autoreleasepool {
            ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
            ABAddressBookAddRecord(book, person, NULL);
        }
    }

    CFRelease(vCardPeople);
    CFRelease(defaultSource);
    CFRelease(book);
}

But I face a problem even before I do any of the importing operations.

If I want to import 50,000 contacts, when my code is trying to create CFArrayRef for my contact data using ABPersonCreatePeopleInSourceWithVCardRepresentation, the memory will keep increasing and reach almost 250MB (Xcode memory debug navigator data).

This is too high for me, because I have other tasks run at the same time might occupy a large memory. So I want to reduce the memory usage before I start importing it.

I was trying to decrease the memory by release some CFReferences that I don't need when importing the contacts like that large CFArrayRef before the importing loop, but memory not going down.

For the test purpose, I commented out the importing loop, only get the array of the contacts. When the whole process done, this view controller will disappear, and next view controller shows up, then the memory back to 80MB.

Is there any possible way to decrease the memory to almost 80MB level before I start importing contacts saved in NSArray without change the view controller.

0

There are 0 best solutions below