1

我正在获取从 plist 排序的值并将它们显示在tableview. 我提供了输入将写入 plist 的自定义类别的功能。但我希望按字母顺序插入。有人可以建议我如何获取indexpath必须插入的行。我使用了以下代码,其中自定义条目将插入到 0 位置

NSInteger section = 0;
NSInteger row = 0;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];

NSDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setValue:newCategoryName forKey:@"name" ];
[categoryDictionary setValue:@"custom.png" forKey:@"image"];

[[self categoriesArray]insertObject:categoryDictionary atIndex:row];
[[self categoriesArray] writeToFile:[self dataFilePath] atomically:YES];

NSArray *indexPathsToInsert = [NSArray arrayWithObject:indexPath];
[[self tableView]insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationRight];
[self.categoriesArray writeToFile:[self dataFilePath] atomically:YES];
4

3 回答 3

2

尝试

NSMutableDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setObject:newCategoryName forKey:@"name" ];
[categoryDictionary setObject:@"custom.png" forKey:@"image"];

//Add new category to array
[self.categoriesArray addObject:categoryDictionary];

//Sort Array
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[self.categoriesArray sortUsingDescriptors:@[sortDescriptor]];

//Write array to plist
[self.categoriesArray  writeToFile:[self dataFilePath] atomically:YES];

NSInteger section = 0;
//Get the index of saved Category item
NSInteger row = [self.categoriesArray indexOfObject:categoryDictionary];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];

[self.tableView insertRowsAtIndexPaths:@[indexPath]
                       withRowAnimation:UITableViewRowAnimationRight];
于 2013-04-23T14:44:07.437 回答
0

在您的表格中,您将使用以下内容获得部分和行

NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
于 2013-04-23T13:57:37.740 回答
0

如果您有一组可排序的项目,则可以使用此代码段作为帮助:

    NSArray *sortedArray = @[@"a" , @"b", @"d", @"c", @"f"];
    sortedArray = [sortedArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSLog(@"%@", sortedArray);

    int c = [sortedArray indexOfObject:@"c"];
    NSLog(@"%d", c);

日志->

(
    a,
    b,
    c,
    d,
    f
)
2

所以你首先将你的对象插入到“toSort”数组中,然后获取它的索引;)

于 2013-04-23T14:00:00.457 回答