我正在获取从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];
答案 0 :(得分: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];
答案 1 :(得分:0)
在您的表格中,您将使用以下
获取部分和行NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
答案 2 :(得分: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”数组中插入你的对象,然后得到它的索引;)