2016-02-27 56 views
1

我想在我的tableView中使用搜索欄。 我有一個NSArray Person(NSObject)。在cellForRow我使用這個代碼:用NSObject內部過濾NSArray

Person *person = [[self.sectionedPersonName objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; 
cell.textLabel.text = person.fullName; 

和搜索欄下面的代碼:

- (void)searchForText:(NSString *)searchText { 
    if (searchText.length > 0) { 
     searchBar = YES; 
    } else { 
     searchBar = NO; 
    } 
     NSLog(@"%@", self.sectionedPersonName); 
     NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText]; 
     self.searchResults = [self.sectionedPersonName filteredArrayUsingPredicate:predicate]; 
} 

self.sectionedPersonName包含此:

(
     (
     "<Person: 0x7fc0f6012650>" 
    ), 
     (
    ), 
     (
    ), 
     (
     "<Person: 0x7fc0f600f8a0>", 
     "<Person: 0x7fc0f60132e0>" 
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
     "<Person: 0x7fc0f6012d80>" 
    ), 
     (
    ), 
     (
     "<Person: 0x7fc0f6012b30>" 
    ), 
     (
     "<Person: 0x7fc0f6010100>" 
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ), 
     (
    ) 
) 

所以我的問題是如何使一個NSPredicate上這個 ? 我已經試過這一點,但不工作:

NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText]; 

錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = (
    "Anna Haro" 
) rhs =)' 

回答

5

你沒有的人一個數組,你的人數組的數組。所以,你不能簡單地過濾數組,因爲所有的比較實際上都是試圖比較字符串數組和字符串。這就是你看到的「奇怪」結果和崩潰的原因。

你最好的選擇是創建你自己的循環遍歷外部數組,然後在每個內部數組上運行你的謂詞。將生成的過濾數組添加到一個新的可變數組中,該數組保存整體結果。

+0

謝謝你!我會嘗試循環。 :) – Viny76