2013-04-23 141 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」數組中,然後獲取它的指數)