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

由于该文件位于您的应用程序包中,因此您将无法保存到它

因此,您需要将新数组保存在 Documents Directory 中

将以下内容添加到您的代码中

//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 回答