我有一个带有类别列表的tableview。我有一个添加按钮,弹出带有textfield的alertview。在该字段中输入的文本应该出现在tableview中。直到这里一切都很好。但它不是得到saved.guess我需要以编程方式将它添加到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);
}
}
答案 0 :(得分: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];
这会将新类别保存到原始文件