Ios UISearchDisplayController的正确实例化
我做了一些搜索,但我仍然不清楚答案。我试图在TableViewController(TVC)中创建UISearchDisplayController的实例 在TVC的标题中,我将searchDisplayController声明为属性:Ios UISearchDisplayController的正确实例化,ios,properties,xcode4.6,searchdisplaycontroller,Ios,Properties,Xcode4.6,Searchdisplaycontroller,我做了一些搜索,但我仍然不清楚答案。我试图在TableViewController(TVC)中创建UISearchDisplayController的实例 在TVC的标题中,我将searchDisplayController声明为属性: @interface SDCSecondTableViewController : UITableViewController @property (nonatomic, strong) NSArray *productList; @property (non
@interface SDCSecondTableViewController : UITableViewController
@property (nonatomic, strong) NSArray *productList;
@property (nonatomic, strong) NSMutableArray *filteredProductList;
@property (nonatomic, strong) UISearchDisplayController *searchDisplayController;
@end
这样做会产生错误:
属性“searchDisplayController”试图使用在超类“UIViewController”中声明的实例变量“\u searchDisplayController”
在实现文件中添加@synthesis searchDisplayController
,消除了错误
有人能帮我理解这个错误吗?我使用的是Xcode 4.6.2,但给我的印象是,属性是从Xcode 4.4开始自动合成的。您会遇到此错误,因为为
searchDisplayController
定义了一个属性。在自定义类中重新定义另一个名为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
。您不应该使用对象:searchDisplayController调用[self-performSelector:@selector(setSearchDisplayController:)代码>如LucOlivierDB所建议。这是一个私人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;
}不应声明searchController属性,因为它将与UIViewController已有的属性冲突(该属性在UISearchDisplayController的init内设置)。