适当的实例化UISearchDisplayController

我做了一些search,答案仍然不清楚。 我正试图在TableViewController(TVC)内创build一个UISearchDisplayController的实例。

在我的TVC的标题中,我宣布了一个searchDisplayController属性:

@interface SDCSecondTableViewController : UITableViewController @property (nonatomic, strong) NSArray *productList; @property (nonatomic, strong) NSMutableArray *filteredProductList; @property (nonatomic, strong) UISearchDisplayController *searchDisplayController; @end 

这样做会产生错误:

属性'searchDisplayController'尝试使用超类“UIViewController”中声明的实例variables“_searchDisplayController”

在实现文件中添加@synthesize searchDisplayController摆脱了错误。

任何人都可以帮我理解这个错误吗? 我使用的是Xcode 4.6.2,但是我觉得属性是自动从Xcode 4.4开始合成的。

你不应该调用[self performSelector:@selector(setSearchDisplayController:) withObject:searchDisplayController]; 正如LucOlivierDB所build议的那样。 这是一个私人的API调用,将让你的应用程序被苹果拒绝(我知道,因为它发生在我身上)。 相反,只要这样做:

 @interface YourViewController () @property (nonatomic, strong) UISearchDisplayController *searchController; @end @implementation YourViewController -(void)viewDidLoad{ [super viewDidLoad]; UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; searchBar.delegate = self; self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; self.searchController.delegate = self; self.searchController.searchResultsDataSource = self; self.searchController.searchResultsDelegate = self; self.tableView.tableHeaderView = self.searchBar; 

}

你得到这个错误,因为UIViewControllersearchDisplayController定义一个属性。 在您的自定义类中重新定义名为searchDisplayController另一个属性会混淆编译器。 如果你想定义一个UISearchDisplayController ,在你的自定义类的- (void)viewDidLoad中实例化一个。

例如:

 - (void)viewDidLoad { [super viewDidLoad]; UISearchBar *searchBar = [UISearchBar new]; //set searchBar frame searchBar.delegate = self; UISearchDisplayController *searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; [self performSelector:@selector(setSearchDisplayController:) withObject:searchDisplayController]; searchDisplayController.delegate = self; searchDisplayController.searchResultsDataSource = self; searchDisplayController.searchResultsDelegate = self; self.tableView.tableHeaderView = self.searchBar; } 

您可以在自定义类中使用self.searchDisplayController来引用searchDisplayController