2

我有两个文本框,当我按下提交时,我想将此文本框的数据存储到 Plist 中。到目前为止我已经完成了编写代码,但问题是如何编写文本框的数据?就像我有 textbox1 和 textbox2 。想将数据存储到 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];

请建议我正确的方法

4

2 回答 2

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];
  }
 }
于 2012-12-06T06:35:50.803 回答
1

在 plist 中创建一个名为 as 的数组title ,然后执行此操作,

-(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];
}

首先尝试一个文本框......确保它会工作......

于 2012-12-06T06:47:52.330 回答