簡體   English   中英

如何處理弱而強的指針?

[英]How to handle weak and strong pointer?

在我的應用程序中,我啟用了ARC,也是新手。 由於沒有經驗的ARC啟用代碼處理,我遇到了一些麻煩

我有一個名為NSMutableArray類型的data的強屬性和相同類型的弱實例變量_currentData

我使用_currentData在應用程序中加載tableView。 我想要顯示的主要集合始終是data變量。 我指出由_currentData變量指向data變量的MutableArray,下面是我的ViewDidLoad

-(void)ViewDidLoad
{
    data=[[NSMutableArray alloc]init];

    //load the data 

    _currentData=data; 
    [myTableView reloadData];

}

我的dataSource方法如下所示

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return [_currentData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     id var=[_currentData objectAtInsex:indexPath.row];
     //.....my drawing methods on the cell View 
     return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id var=[_currentData objectAtInsex:indexPath.row];
    NSlog(@"var %@",var);
}

以上代碼工作正常,每當我點擊單元格時,我都會打印var,直到我打算實現搜索欄,如下面的代碼所示

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    _currentData =[data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name contains[c] '%@'",searchText]]];//  Object with attribute name
    [myTableView reloadData];
}

上面的代碼工作正常,在tableView中顯示過濾結果,但當我點擊任何一行時我打印空

我不知道哪里出了問題。

currentData只是指向data時,它就currentData弱。 只要data是各地, currentData將被保留,當data消失,所以將currentData

您的問題是您將currentData分配給一個新值:

_currentData =[data filterUsingPredicate:myPredicateVariable];

或者本來如果filterUsingPredicate:返回的值(我想你的意思filteredArrayUsingPredicate:這只會在范圍,直到方法結束。 調用reloadData時, currentData已被釋放。 您需要分配[data filteredArrayUsingPredicate:myPredicateVariable]; 到一個強大的屬性或ivar,或聲明currentData為強。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  {   
    _currentData =[data filterUsingPredicate:myPredicateVariable];
    [myTableView reloadData];
}

這里有錯誤邏輯。 在修改可變數組時過濾數組(就地)。 你想要的是得到一個新的過濾數組,否則它只能工作一次/很少

所以

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  {   
    NSMutableArray *newData = [data filteredArrayUsingPredicate:myPredicateVariable];
    _currentData = newData;
    [myTableView reloadData];
}

然后_currentData最強大,因為沒有其他人保留新陣列。 如果它是__weak,則只要newData被釋放就會變為nil

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM