1

カテゴリのリストを含むテーブルビューがあります。テキストフィールドを含むアラートビューをポップする追加ボタンがあります。そのフィールドに入力されたテキストはテーブルビューに表示されます。ここまではすべて問題ありませんが、保存されません。プログラムでplistに追加する必要があると思います。誰かがそれを手伝ってくれますか?

//Reading data from plist.
NSString *categoryFile = [[NSBundle mainBundle]pathForResource:@"Categories" ofType:@"plist"];
self.categoryList = [[NSMutableArray alloc]initWithContentsOfFile:categoryFile];


//adding to the tableView
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1)
{
    UITextField *newCategoryName = [alertView textFieldAtIndex:0];
    NSInteger section = 0;
    NSInteger row = 0;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    NSString *extraContent = newCategoryName.text;
    [[self categoryList]insertObject:extraContent atIndex:row];
    NSArray *indexPathsToInsert = [NSArray arrayWithObject:indexPath];
    [[self tableOfCategories]insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationRight];
    NSLog(@"%@",newCategoryName.text);
}
}
4

1 に答える 1

1

ファイルはアプリバンドル内にあるため、保存することはできません

そのため、新しい配列をドキュメント ディレクトリに保存する必要があります。

以下をコードに追加します

//First change your load code to the following
//try to load the file from the document directory
NSString *categoryFile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Categories"];

//if no file there, load from bundle
if(![[NSFileManager defaultManager] fileExistsAtPath:categoryFile])
{
    categoryFile = [[NSBundle mainBundle]pathForResource:@"Categories" ofType:@"plist"];
}
//Load the array
self.categoryList = [[NSMutableArray alloc]initWithContentsOfFile:categoryFile];

... after adding a new category

[[self categoryList]insertObject:extraContent atIndex:row];
//After adding the new element, save array
[self.categoryList writeToFile: categoryFile atomically:YES];

これにより、新しいカテゴリが元のファイルに保存されます

于 2012-06-12T14:09:26.890 に答える