2011-08-05 46 views
1

檢索自定義對象我創建一個具有像ID和標題,描述等一些屬性的自定義對象...性能問題,同時從陣列

我把它添加到一個數組。 (該數組可能包含超過500個值)。

而且我用下面的代碼來檢索自定義對象,

-(CustomObjects *)getObjectWithId:(int)id { 

    CustomObjects *objCustomObjects = nil; 

    for (CustomObjects *customObjects in arrayCustomObjects) { 

     if (customObjects.id == id) { 

      objCustomObjects = customObjects; 
      break; 
     } 
    } 


    return objCustomObjects; 
} 

但是它有一些性能問題,因爲我使用的函數,在UIScrollView的捏調用。

如何提高抓取對象的性能?

在此先感謝,

+0

我希望你實際上並沒有使用'id'作爲參數,以你的方法 - 這是在Objective-C的保留字... :) – Mac

回答

0

你可以更好的使用NSDictionaryid的關鍵。您可以輕鬆地從字典中獲取對象。

它可以滿足您的要求嗎?

0

您可以使用NSPredicate檢查id是否等於您正在查找的那個,並使用此謂詞通過調用filteredArrayUsingPredicate:來簡單地過濾自定義對象。

爲了提高性能,我會盡量推遲無論你想通過不直接調用,做在你的滾動視圖繁重的工作的函數來計算,而是叫[self performSelector:... withObject:nil afterDelay:0];其推遲計算到下一個週期runloop。如果您在調用performSelector之前檢查計劃是否已經計劃好,那麼實際上應該可以減少計算的頻率,同時保持清晰的界面。

-1

使用NSPredicate: -

您將收到與具有傳遞了ID的對象的過濾陣列; NSPredicate * predicate = [NSPredicate predicateWithFormat:@「id ==%@」,id];} Nspredicate * predicate = [NSPredicate predicateWithFormat:@「id ==%@」,id];

NSArray * filtered = [arrayCustomObjects filteredArrayUsingPredicate:predicate];

+0

謂詞的事情真的不能做任何事情比聰明線性搜索他已經在做,可以嗎? – zoul

1

字典對此更好。唯一的問題是你不能有NSDictionary與原始int鍵,所以你必須包裝idNSNumber

- (void) addCustomObject: (CustomObject*) obj { 
    NSNumber *wrappedID = [NSNumber numberWithInt:[obj idNumber]]; 
    [dictionary setObject:obj forKey:wrappedID]; 
} 

- (CustomObject*) findObjectByID: (int) idNumber { 
    NSNumber *wrappedID = [NSNumber numberWithInt:[obj idNumber]]; 
    return [dictionary objectForKey:wrappedID]; 
} 

字典(也稱爲hash table)不必經過所有的值來找到合適的人,它根據按鍵巧妙安排的所有值,以便它可以跳轉到合適的一個或靠近它。你對這個數組所做的事情叫做linear search,它效率不高。

0

如果您想快速查找,則必須拋棄數組以支持字典。

如果你想通過鍵和索引訪問對象,那麼你需要兩個集合中的對象,並確保它們同步。

我已經爲這個名爲CWOrderedDictionary做了助手類。它是NSMutableDictionary的一個子類,允許通過密鑰(如同任何字典那樣)以及使用與NSMutableArray相同的方法通過索引來訪問對象。

我的類可用於靈感或者是從這裏開始:https://github.com/jayway/CWFoundation/

-1

而不是int只使用[NSNumber numberWithInt:],我沒有在你定的代碼一些變化。

-(CustomObjects *)getObjectWithId:(NSNumber*)id {//changed int to NSNumber 

    CustomObjects *objCustomObjects = nil; 

    NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF.id==%@",id]; 
    NSArray *result = [array filteredArrayUsingPredicate:bPredicate]; 
//return filtered array contains the object of your given value 

    if([result count]>0) 
     objCustomObjects = [result objectAtIndex:0]; 

    } 
    return objCustomObjects; 
} 
+0

再一次,你覺得'filteredArrayUsingPredicate:'可以做比海報已經做的線性搜索更聰明的事情嗎?你是否簡介了代碼?它必須比原始版本慢。 – zoul