数据重新加载后保持UITableView选定的值

时间:2012-05-18 20:54:17

标签: objective-c ios

我有一个表从JSON调用加载值,每5秒刷新一次。每次表格更改并添加新单元格时,当前选定的单元格将成为重新加载时最后一个单元格之上的单元格。您可以在我的get_counter选择器中看到我正在尝试执行此操作。提前致谢!我在ObjC仍然很新,所以只是想学习:)

- (void)viewDidLoad {
[super viewDidLoad];
repeat_timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(check_new) userInfo:nil repeats:YES];

}

-(void)check_new{

    NSString *ret;
    ret=[MyWebFunction is_new_orders:appDelegate.user_id Order_number:[[response_array objectAtIndex:0] objectForKey:@"order_id"] Type:type];

    if([ret isEqualToString:@"yes"]){
        [indicator startAnimating];
        [self performSelector:@selector(get_counter) withObject:nil afterDelay:0.0005];

    }
}


-(void)get_counter{

jsonString = [[NSMutableString alloc] initWithData:[MyWebFunction get_orders:appDelegate.user_id Type:type Limit:limit] encoding:NSUTF8StringEncoding];;
response_array = [[jsonString JSONValue] retain];
[indicator stopAnimating];

//this is my attempt at retaining the value :)    
NSIndexPath *ipath = [table indexPathForSelectedRow];
NSLog(@"iPath: %@",ipath);
[table reloadData];
[table selectRowAtIndexPath:ipath animated:NO scrollPosition:UITableViewScrollPositionNone];


if([response_array count]>0){

    total=[[[response_array objectAtIndex:0] objectForKey:@"total_orders"] intValue];
    checksArray=[[NSMutableArray alloc] init];

    for(int i=0;i<response_array.count;i++){

        [checksArray addObject:@"0"];
    }
}
sel_item_id=[[NSMutableArray alloc] init];
all_ids=nil;

if(repeat_timer){
    [repeat_timer invalidate];
    repeat_timer=nil;
repeat_timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(check_new) userInfo:nil repeats:YES];
}

}

1 个答案:

答案 0 :(得分:2)

我可能完全偏离这一点,但这可能是你的问题。

NSIndexPath *ipath = [table indexPathForSelectedRow];

对我而言,这看起来像是在指定所选行。因此,当您更新表时,ipath也会更新。

尝试:

NSIndexPath *ipath = [[table indexPathForSelectedRow] copy];

另一件事是,如果你添加一个新行,那么行索引会有变化。 试试这个:

- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell

所以它会是:

NSIndexPath *ipath = [table indexPathForSelectedRow];
UITableViewCell *cell = [table cellForRowAtIndexPath:ipath];
[table reloadData];
[table selectRowAtIndexPath:[table indexPathForCell:cell] animated:NO scrollPosition:UITableViewScrollPositionNone];

很多信息,但希望那里的东西会有所帮助。