簡體   English   中英

如何在數組內部保存對象索引,然后在更新數組時顯示索引位置是否已更改

[英]How to save objects indexes inside an array and then display if the position of index has changed when the array gets updated

我正在制作一個應用程序,從XML文件中獲取數據,將其解析為數組,然后填充一個TableViewController。

現在,我想找到一種保存此顯示順序的方法,因此,每當我的應用重新加載數據時,它都會檢測對象是否移動了索引,並相應地顯示和UP / DOWN / EQUAL符號。

E.g:

Loads data

1 = B
2 = A
3 = C

Reloads data

1 ^ C
2 = A
3 - B

我不確定如何才能做到這一點,有人可以幫助我嗎?

謝謝。

您可以通過多種方式執行此操作,但是indexOfObject:方法將是實現此目標的最佳選擇。 使用該方法,您可以編寫如下內容:

    NSArray *ar1 = @[@"first", @"second", @"third"];

    NSLog(@"%d", (unsigned)[ar1 indexOfObject:@"third"]);

它將注銷2

基於此,以下內容應該適合您。

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

對我來說輸出:

Obj: third Old idx: 2 new idx: 0 
Obj: first Old idx: 0 new idx: 1 
Obj: second Old idx: 1 new idx: 2

我認為您需要保留舊數據的副本,然后在更新到達時比較數據。 就像是:

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

假設oldData包含上次獲取的數據,而newData包含剛剛獲取的數據

暫無
暫無

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

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