2013-04-17 90 views
2

在xcode中,我有一個數據庫,可以從聯機sql數據庫請求並可以存儲到數組或NSDictionary或其他類型中。另外,應用程序中會生成與數據庫的其中一列對應的數字數組。如何使用另一個數組過濾對象數組以定義要過濾的對象

我想過濾數據庫,只顯示涉及生成數組的對象。一旦過濾,我想列出一個字符串的結果。如果需要,來自在線服務器的數據庫可以存儲在NSArray或NSDictionary中,也可能存儲其他我不知道的格式。

該過程看起來像這樣:

數據庫陣列:生成的陣列:如下

ID | Name   ID      FilteredNames 
     | 
1A | Hannah   1A       Hannah 
2A | John   1B       Steve 
3A | Peter   2B       Zara 
1B | Steve 
2B | Zara 
3B | Kyle 

的所得陣列「FilteredNames」轉換爲字符串列表:濾波該數據庫後合成陣列:

NamesString = @"Hannah, Steve, Zara" 

然後我打算在NamesString傳遞給一個標籤,如下所示:

label.text=NamesString; 

,因此在視圖中的標籤只是表明:

       Hannah, Steve, Zara 

我非常需要這整個過程的幫助。

回答

1

編輯按照Martin的評論,將謂詞格式改爲更合適的一種。

- (NSArray *)filterObjects:(NSArray *)objects withNames:(NSArray *)names { 
    return [objects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name IN %@", names]]; 
} 

// given that the 'objects' array is what you get from server 
    NSArray *objects = @[ 
         @{@"id" : @"1A", @"name" : @"Hannah"}, 
         @{@"id" : @"2A", @"name" : @"John"}, 
         @{@"id" : @"3A", @"name" : @"Peter"}, 
         @{@"id" : @"1B", @"name" : @"Steve"}, 
         @{@"id" : @"2B", @"name" : @"Zara"}, 
         @{@"id" : @"3B", @"name" : @"Kyle"} 
         ]; 

    NSArray *filteredObjects = [self filterObjects:objects withNames:@[@"Hannah", @"John", @"Zara"]]; 
    NSLog(@"filteredObjects: %@", filteredObjects); // prints them out as dictionaries 

    NSString *unitedNames = [[filteredObjects valueForKeyPath:@"@unionOfObjects.name"] componentsJoinedByString:@", "]; 
    NSLog(@"unitedNames: %@", unitedNames); // comma separated array of names 
+0

謝謝先生,經過我設法讓它按照你的建議工作,非常感謝。 – PixelWhip

+0

我不會推薦使用字符串格式化函數來創建一個複雜的謂詞。如果任何搜索字符串包含字符''',則立即中斷。實際上,這裏有一個更簡單的解決方案,使用'@「名稱IN%@」,names'。在更復雜的情況下,您可以通過NSCompoundPredicate來創建AND/OR組合。 –

+0

@MartinR,謝謝你,這將幫助我在將來 – Eugene

相關問題