iphone - 保存和显示 textfield.text

标签 iphone ios xcode uitableview plist

我有一个带有类别列表的表格 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/

相关文章:

ios - Xcode Storyboard显示与模拟器不同的设计?

ios - 容器 View 中的 UIView 未显示

ios - 如何从今天获取过去一周的日期?

iphone - ConvertToWorld-/NodeSpace 如何工作?

ios - 围绕其中心点旋转 UIImageView?

ios - 核心数据获取特定对象

xcode - 在项目中查找下一个的快捷方式

iphone - 需要 VFR 阅读器中的列表搜索功能

ios - 没有这样的模块,swift,xcode 6.2

ios - 如何处理IOS图像裁剪中的图像旋转问题