[英]How to save objects indexes inside an array and then display if the position of index has changed when the array gets updated
I am making an app where i get data from an XML file, i parse it to an Array, and then it populates a TableViewController. 我正在制作一个应用程序,从XML文件中获取数据,将其解析为数组,然后填充一个TableViewController。
Now i want to find a way to save this display order, so whenever my app reloads the data it detects if the object has moved indexes or not and display and UP/DOWN/EQUAL sign accordingly. 现在,我想找到一种保存此显示顺序的方法,因此,每当我的应用重新加载数据时,它都会检测对象是否移动了索引,并相应地显示和UP / DOWN / EQUAL符号。
E.g:
Loads data
1 = B
2 = A
3 = C
Reloads data
1 ^ C
2 = A
3 - B
I'm not sure how i can accomplish this, can anyone help me out? 我不确定如何才能做到这一点,有人可以帮助我吗?
Thank you. 谢谢。
There are multiple ways that you could do this, but the indexOfObject:
method is going to be your best bet for making it happen. 您可以通过多种方式执行此操作,但是indexOfObject:
方法将是实现此目标的最佳选择。 With that method you could write something like: 使用该方法,您可以编写如下内容:
NSArray *ar1 = @[@"first", @"second", @"third"];
NSLog(@"%d", (unsigned)[ar1 indexOfObject:@"third"]);
And it would log out 2
. 它将注销2
。
Based on that something like the following should work for you. 基于此,以下内容应该适合您。
NSArray *ar1 = @[@"first", @"second", @"third"];
NSArray *ar2 = @[@"third", @"first", @"second"];
[ar2 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (idx != [ar1 indexOfObject:obj]) {
NSLog(@"Obj: %@ Old idx: %ld new idx: %ld", obj, [ar1 indexOfObject:obj], idx);
}
}];
For me that outputs: 对我来说输出:
Obj: third Old idx: 2 new idx: 0
Obj: first Old idx: 0 new idx: 1
Obj: second Old idx: 1 new idx: 2
I think you need to keep a copy of the old data and then when the update arrives compare the data. 我认为您需要保留旧数据的副本,然后在更新到达时比较数据。 Something like: 就像是:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSObject * obj = self.newData objectAtIndex:indexPath.row];
int oldIndex = [self.oldData indexOfObject:obj];
if (oldIndex == NSNotFound) { //new object
//do something with the new object
}
else
{
//do something with the oldIndex
}
}
Assuming oldData
contains the data fetched last time and newData
contains the just recived data 假设oldData
包含上次获取的数据,而newData
包含刚刚获取的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.