簡體   English   中英

如何像其他應用程序一樣快速閱讀地址簿(如Viber,Whatsapp ......)

[英]How to read the Address Book as fast as other apps (like Viber, Whatsapp…)

我正在編寫一個應用程序,我需要閱讀地址簿數據來搜索一些感興趣的聯系人,類似於現在許多應用程序所做的事情(如Viber,Whatsapp,Tango ......)。 我需要進行匹配,因此我將數據發送到服務器並回復客戶端哪些聯系人在其設備上安裝了相同的應用程序。

我的想法的邏輯或機制沒有問題,我的問題是速度! 我能夠做我想要的但是這個過程需要27秒才能完成,iPhone4上有500個聯系人。 如果我們嘗試Viber或Whatsapp(或任何類似的應用程序),在相同的設備上,該過程只需不到5秒。

我的方法很簡單,我做一個for循環並讀取所有內容。 我怎么能做同樣的事情,但比其他應用程序更快?

這是我使用的代碼:

    //variable definitions
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFMutableArrayRef peopleMutable = CFArrayCreateMutableCopy(kCFAllocatorDefault, CFArrayGetCount(people), people);

    //sort the contents of the Mutable Array
    CFArraySortValues(peopleMutable, CFRangeMake(0, CFArrayGetCount(peopleMutable)), (CFComparatorFunction) ABPersonComparePeopleByName, (void*) ABPersonGetSortOrdering());

    //read the Address Book
    NSString *fullName, *number;
    ABRecordRef record = ABPersonCreate();
    ABMutableMultiValueRef multi;
    int contactID;
    int nameCount=0;//used to count the names in the string to send to server
    NSMutableString *strNamesToSend = [[NSMutableString alloc] init];

    for(CFIndex i=0; i< CFArrayGetCount(people); i++)
    {
        record = CFArrayGetValueAtIndex(people, i);
        multi = ABRecordCopyValue(record, kABPersonPhoneProperty);

        //Contact ID
        contactID = (int)ABRecordGetRecordID(record);

        //Full Name
        fullName = [NSString stringWithFormat:@"%@ %@", (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty), (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty)];
        fullName = [fullName stringByReplacingOccurrencesOfString:@" (null)" withString:@""];

        //fill data into AddressBook Table
        if(dbOpen == SQLITE_OK)
        {
            //pure sqlite3 work to save the names in my app
        }

        //Get multiple numbers from each user (if any)
        for(CFIndex j=0; j<ABMultiValueGetCount(multi); j++)
        {
            number = (NSString *)ABMultiValueCopyValueAtIndex(multi, j);

            nameCount++;

            //fill data into AllNumbers Table
            if(dbOpen == SQLITE_OK)
            {
                 //another sqlite3 work to save the numbers
            }
        }

        //send to the server every 29 numbers so we don't send all the 500 numbers at once
        if(nameCount > 29)
        {
            //send to server
        }

您是否嘗試過分析代碼? 分析器應該能夠快速識別代碼的緩慢部分。

從一個非常簡短的檢查,我注意到你在每次迭代時計算數組大小而不是一次。 將它移出你的循環:

int count = CFArrayGetCount(people);
for (CFIndex i = 0; i < count; i++)

您沒有詳細說明您正在進行的SQL調用,但是您正在檢查SQLITE_OK這一事實意味着您每次都要通過循環打開數據庫。 如果是這種情況,您應該將此調用移到循環之外,而不是每次都打開數據庫。

我注意到nameCount沒有被重置,這意味着一旦它達到29,你的if case將每次都被命中,導致大量的網絡請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM