【问题标题】:Not able to retain NSMutableArray objects (I'm using ARC)无法保留 NSMutableArray 对象(我正在使用 ARC)
【发布时间】:2013-03-14 23:22:16
【问题描述】:

我试图在表格视图中显示在 Twitter 应用程序的搜索字段中搜索的关键字,以及为此搜索返回的推文数量。 从主 ViewController,我试图以编程方式创建另一个表视图。并且每当我将一个对象添加到 NSMutableArray(这是我要显示的表的数据)时,该对象就会存储在其中,但对于下一个函数调用,该数组不会保留其值。由于我使用的是 ARC,因此我也不能使用“保留”和“释放”语句。

我该如何解决这个问题?

请帮忙。

@interface AppViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

@property (strong,nonatomic) NSMutableArray *searchWords;
@property (strong,nonatomic) NSMutableArray *searchCount;
@property (strong,nonatomic) NSString *count;
@property (strong,nonatomic) UITableView *historyTable;


@property (strong, nonatomic) IBOutlet UITextField *searchTextField;
- (IBAction)showHistory:(id)sender;

@end

@implementation TwitterSearchViewController
@synthesize searchTextField;

@synthesize searchCount,searchWords,count,historyTable; 

- (void)viewDidLoad
{

    count=[[NSString alloc] init];
    searchWords=[[NSMutableArray alloc] init];
    searchCount=[[NSMutableArray alloc] init];
    historyTable=[[UITableView alloc] init];

    [super viewDidLoad];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([[segue identifier] isEqualToString:@"transitionToSearchResults"]) 
    {
        NSLog(@"Count of searchWords before:%lu",(unsigned long)[searchCount count]);
        //This prints 0 every time 

        [searchWords addObject:[searchTextField text]];

        NSLog(@"Count of searchWords:%lu",(unsigned long)[searchWords count]);
        //This prints 1 every time              


        TWRequest *requestError = [[TWRequest alloc] initWithURL:[NSURL URLWithString:searchURL] parameters:nil requestMethod:TWRequestMethodGET];
        //searchURL is used to get the tweets using Twitter API

        // Send the Twitter Search request and create a handler to handle the Search response
        [requestError performRequestWithHandler:^(NSData *searchResponse, NSHTTPURLResponse *requestResponse, NSError *error) 
         {

                 // Extract the Twitter messages from search response
                 NSArray *tweetMessages = [searchResultsDict objectForKey:@"results"];

                 // Set the Data Source for the Table in TwitterSearchResultsViewController
                 // which displays the search results nicely
                 [searchViewController setTweetMessages:tweetMessages];
                 // Update the table view
                 [searchViewController updateTableView];
                 count=[[NSString alloc] initWithFormat:@"%lu",(unsigned long)[tweetMessages count]];

             }
         }];
        [searchCount addObject:count];
    }
}

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

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifier=@"HistoryCell";
    UITableViewCell *newCell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(newCell==nil){
        newCell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier];
    }

    [[newCell textLabel] setText:[searchWords objectAtIndex:[indexPath row]]];
    [[newCell detailTextLabel] setText:[searchCount objectAtIndex:[indexPath row]]];

    return newCell;


}

- (IBAction)showHistory:(id)sender {
    //historyTable=[[UITableView alloc] init];
    historyTable.dataSource=self;
    historyTable.delegate=self;
    NSLog(@"Histroy count:%ld",(long)[historyTable numberOfRowsInSection:0]);
    //Since the mutable arrays are not retaining their values, the number of rows in my     table is always zero
    self.view=historyTable;
    self.title=@"Search History";
}
@end

【问题讨论】:

  • 您正在prepareForSegue 中添加对象。什么时候再调用一次?你会回到这个控制器吗?如果是,怎么做?
  • 我严重怀疑您的问题与您的阵列没有保留其内容有关。尝试将日志放入 viewDidLoad。当您来回访问此控制器时,它是否记录了多次?
  • 是的,我在 viewDidLoad 中放了一条日志消息,这有助于我解决问题。由于每次切换回视图时都会调用 viewDidLoad 方法,因此我的值丢失了。我现在修好了,谢谢! :)

标签: ios objective-c nsmutablearray automatic-ref-counting retain


【解决方案1】:

在计算计数后输入您的[searchCount addObject:count]; 代码。

[requestError performRequestWithHandler:^(NSData *searchResponse, NSHTTPURLResponse *requestResponse, NSError *error) 
             {

                     // Extract the Twitter messages from search response
                     NSArray *tweetMessages = [searchResultsDict objectForKey:@"results"];

                     // Set the Data Source for the Table in TwitterSearchResultsViewController
                     // which displays the search results nicely
                     [searchViewController setTweetMessages:tweetMessages];
                     // Update the table view
                     [searchViewController updateTableView];
                     count=[[NSString alloc] initWithFormat:@"%lu",(unsigned long)[tweetMessages count]];

                     [searchCount addObject:count];
                 }
             }];

【讨论】:

  • 谢谢。我也刚想通这个。但是我更改了 viewDidLoad 中的代码来检查这些变量是否为零,如果是,那么我才分配和初始化它们。再加上这行代码的移动,就彻底解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 2013-04-29
  • 1970-01-01
  • 2014-01-13
相关资源
最近更新 更多