0

I have a table that is loading values from a JSON call that refreshes every 5 seconds. Every time the table changes, and a new cell is added, the currently selected cell becomes the one above the last one on the reload. You can see in my get_counter selector where I am trying to do it. Thanks in advance! I am still very new at ObjC so just trying to learn :)

- (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];
}

}
4

1 回答 1

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];

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

于 2012-05-18T23:29:34.740 回答