我有两个文本框,我想在我按提交时将此文本框的数据存储到Plist中。 到目前为止我经历了编写代码,但问题是如何写入文本框的数据?就像我有textbox1和textbox2 .want将数据存储到plist
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Comments" ofType:@"plist"];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSMutableDictionary *newComment = [NSMutableDictionary dictionary];
[newComment setValue:commentTitle.text forKey:@"title"];
[newComment setValue:comment forKey:@"comment"];
[plistArray addObject:newComment];
[plistArray writeToFile:filePath atomically:NO];
请建议我正确的方法
答案 0 :(得分:3)
让您的文本框为textbox1和textbox2
- (IBAction) saveData
{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Comments.plist"];
// set the variables to the values in the text fields
self.title = textbox1.text;
self.comment = textbox2.text;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: title, comment, nil] forKeys:[NSArray arrayWithObjects: @"title ", @"comment", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(@"Error in saveData: %@", error);
[error release];
}
}
答案 1 :(得分:1)
在名为title
的plist中创建一个数组,然后执行此操作,
-(void) SubmitAction {
NSString *path = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [path stringByAppendingPathComponent:@"your_plist_name"];
NSMutableDictionary *plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
NSMutableArray *titleArray=[plistDict valueForKey:@"title"];
[titleArray addObject:textbox1.text];
[plistDict setValue:titleArray forKey:@"title"];
[plistDict writeToFile:finalPath atomically:NO];
}
首先尝试使用一个文本框.....确定它会起作用....