2013-04-23 143 views
1

我得到的值是从plist中排序并显示在tableview中的值。我正在提供输入将写入plist的自定义类别的功能。但我希望按照排序的字母顺序插入。有人可以建议我如何获得必须插入的行的indexpath。我已经使用了下面的代码,自定义项将在0位置在Sorted Array中获取IndexPath

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

回答

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

***终止应用程序由于未捕获的异常“NSUnknownKeyException”,原因:'[<__ NSCFString 0x8b7e580> valueForUndefinedKey:]:这个类不是关键字编码密钥值。“ – 2013-04-24 06:46:47

+0

当使用排序描述符时,我得到了上述错误 – 2013-04-24 06:47:42

+0

@ChandraSekhar你可以把断点,告诉我你的代码破坏的地方。 self.categoriesArray只包含字典对象,它们都有一个关键的“名称”,我假设这些都是这样的。请检查,以及 – Anupdas 2013-04-24 06:56:55

0

插在你的餐桌,你会得到部分和使用行以下

NSInteger section = indexPath.section; 
NSInteger row = indexPath.row; 
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”数组中,然后获取它的指数)