2013-05-28 55 views
2

我做了一些搜索,答案仍然不清楚。我正試圖在TableViewController(TVC)內創建一個UISearchDisplayController的實例。適當的實例化UISearchDisplayController

在我的TVC的頭,我宣佈一個searchDisplayController作爲一個屬性:

@interface SDCSecondTableViewController : UITableViewController 

@property (nonatomic, strong) NSArray *productList; 
@property (nonatomic, strong) NSMutableArray *filteredProductList; 
@property (nonatomic, strong) UISearchDisplayController *searchDisplayController; 

@end 

否則可能會產生錯誤:

Property 'searchDisplayController' attempting to use instance variable '_searchDisplayController' declared in super class 'UIViewController'

在實現文件中添加@synthesize searchDisplayController擺脫了錯誤的。

任何人都可以幫我理解這個錯誤嗎?我使用的是Xcode 4.6.2,但我的印象是,從Xcode 4.4開始自動合成屬性。

回答

3

由於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.searchDisplayControllersearchDisplayController

7

您不應該按照LucOlivierDB的建議調用[self performSelector:@selector(setSearchDisplayController:) withObject:searchDisplayController];。這是一個私人的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; 

}