我有一个带有类别列表的表格 View 。我有一个添加按钮,它会弹出一个带有文本字段的警报 View 。在该字段中输入的文本应该出现在表格 View 中。到这里为止一切都很好。但事实并非如此正在保存。我想我需要以编程方式将它添加到 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);
}
}
最佳答案
由于该文件位于您的应用程序包中,因此您将无法保存到它
因此您需要将新数组保存在文档目录中
将以下内容添加到您的代码中
//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];
这会将新类别保存到原始文件中
关于iphone - 保存和显示 textfield.text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10997861/