Proper instantiation of UISearchDisplayController
我进行了一些搜索,但我仍然不清楚答案。我正在尝试在 TableViewController (TVC) 中创建 UISearchDisplayController 的实例。
在 TVC 的标题中,我将 searchDisplayController 声明为属性:
1
2 3 4 5 6 7 |
@interface SDCSecondTableViewController : UITableViewController
@property (nonatomic, strong) NSArray *productList; @end |
这样做会产生错误:
Property ‘searchDisplayController’ attempting to use instance variable ‘_searchDisplayController’ declared in super class ‘UIViewController’
在实现文件中添加 @synthesize searchDisplayController 消除了错误。
谁能帮我理解这个错误?我使用的是 Xcode 4.6.2,但我的印象是属性是从 Xcode 4.4 开始自动合成的。
你不应该像 LucOlivierDB 建议的那样调用 [self performSelector:@selector(setSearchDisplayController:) withObject:searchDisplayController];。这是一个私有 API 调用,它会让你的应用被 Apple 拒绝(我知道,因为它发生在我身上)。而是这样做:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@interface YourViewController ()
@property (nonatomic, strong) UISearchDisplayController *searchController; @end @implementation YourViewController –(void)viewDidLoad{ self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; self.tableView.tableHeaderView = self.searchBar; |
}
- 不应该声明 searchController 属性,因为它会与 UIViewController 已经拥有的属性冲突(在 UISearchDisplayController 的 init 中设置)。
您收到此错误是因为 UIViewController 为 searchDisplayController 定义了一个属性。在自定义类中重新定义另一个名为 searchDisplayController 的属性会使编译器感到困惑。如果要定义 UISearchDisplayController,请在自定义类的 – (void)viewDidLoad 中实例化一个。
示例:
1
2 3 4 5 6 7 8 9 10 11 12 13 |
– (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。
来源:https://www.codenong.com/16801810/