我的理解,你需要搜索和顯示來自3個不同陣列的內容的一個通用implementaion。所以,在這種情況下,我通常會創建基本控制器類,它將具有搜索欄和tableView,所有搜索功能以及指向數據源數組的指針。 直接在瀏覽器中輸入,所以可能會出現錯誤。
@interface BaseListController : UIViewController
{
UITableView* _tableView;
UISearchBar* _searchBar;
}
@property NSArray * source;
@poperty (readonly) NSArray * founded;
@end;
比,你需要確保所有3個的數組對象支持你的特殊查詢界面:
@protocol SearchedItem <NSObject>
@required
- (NSString *)searchKey;
@end
這是你的搜索方法後,將看起來像:
- (void)searchForKey:(NSString *)searchText
{
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"searchKey contains[cd] %@", searchText];
_founded = [self.source filteredArrayUsingPredicate:predicate];
[_tableView reloadData];
}
編輯:擴展答案如何以及爲什麼需要使用@protocol
首先讀this aticle,它清楚地說明了如何使用@protocol。
我仍然不知道你將保留在這3個數組中。但讓我們說你會保留3個不同類的對象繼承fom NSObject,並且可以稱它們爲Chapter
,Recipe
和Ingredient
。他們每個人都有自己獨特的名字。爲了獨立處理他們的混音,這些類必須有一些共同點。這個常見的事情將是單一接口 - 它們都必須符合你定義的@協議。這意味着,它不管這個對象的類是什麼,但是你可以確定它會響應被調用的協議的方法。代碼示例:
// .h file
@interface Chapter : NSObject <SearchedItem>
@property NSString * chapterName;
@property NSArray * recipes;
@end
@interface Recipe : MSObject <SearchedItem>
@property NSString * recipeName;
@property NSArray * ingredients;
@end
@interface Ingredient : NSObject <SearchedItem>
@property NSString * prettyName;
@property NSNumber * enoughCount;
@end
// .m file There you must implement protocol's requied method!
@implementation Chapter
- (NSString *)searchKey{
return self.chapterName;
}
@end
@implementation Recipe
- (NSString *)searchKey{
return self.recipeName;
}
@end
@implementation Ingredient
- (NSString *)searchKey{
return self.prettyName;
}
@end
所以現在,在你cellForRowAtIndexPath:
方法,你可以很容易得到單行標題不知道哪些數據,目前有:
id<SearchedItem> item = self.source; //self.founded
cell.titleLabel.text = [item searchKey];
附:如果您在您的陣列中存儲簡單的NSString,則不需要任何協議
搜索1個數組或兩個或三個之間的主要區別是什麼? – Andy
對不起,我不明白你的意思? –
我試圖瞭解你的問題,如果你有一個工作搜索每個單獨的數據數組,但在跨所有三個搜索時觸擊塊。由於沒有代碼,因此現在很難提出任何建議。 – Andy