【问题标题】:How can I retain the data stored in plist from UITextField when application is restarted?重新启动应用程序时,如何保留 UITextField 中存储在 plist 中的数据?
【发布时间】:2010-04-21 13:10:22
【问题描述】:

我正在使用 plist 来存储在 UITextFields 中输入的数据。但是,当我重新启动我的应用程序时,之前输入的所有数据都被删除了。如何保留 Plist 中的数据。我有一个 UITableView,当触摸一个单元格时,会出现一个带有两个 UITextField 的视图。名称字段和描述字段。我就是这样存储数据的。

我的代码是。

-(void)save:(id)sender
{

    indexOfDataArray = temp;

    NSString *string1 = [[NSString alloc]init];
    NSString *string2 = [[NSString alloc]init];
    string1 = nameField.text;
    string2 = descriptionField.text;
    NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:string2, string1, nil];
    //NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value", string2, @"key", string1, @"index", [NSNumber numberWithInt:indexOfDataArray], nil];

    [myArray addObject:myDict];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"tableVideoData.plist"]; 

    [myArray writeToFile:path atomically:YES];

    UIAlertView *alertMesage = [[UIAlertView alloc] initWithTitle: @"Save Alert" message:@"The data entered is saved" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil] ;
    [alertMesage show];
    [alertMesage release];
}

文件的路径是

/Users/srikanth/Library/Application Support/iPhone Simulator/User/Applications/31DEFEE7-A468-44BD-B044-53BEA3391C1A/Documents

但问题是每次我重新启动应用程序时,数据都会在新文件夹的新 plist 文件中创建。那么,如何将数据存储在一个 plist 中?

谢谢。

【问题讨论】:

    标签: iphone cocoa-touch uitableview uitextfield


    【解决方案1】:

    错误是由于数组太小而触发的;您尝试在超出数组上限的索引处插入对象。

    如果要同时保留索引和数据,请将索引存储在字典中:

    NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value", string2, @"key", string1, @"index", [NSNumber numberWithInt:indexOfDataArray], nil];
    [myArray addObject:myDict];
    

    【讨论】:

    • 谢谢。但是我怎样才能保留 pList 中的数据。每次我重新启动应用程序时它都会被删除。
    • 你为什么不使用 NSUserDefaults?
    • 麦克马德是对的。如果您需要数据的持久性,您可以使用 NSUserDefaults。见developer.apple.com/iphone/library/documentation/Cocoa/…
    • 我使用了 NSUserDefaults 但数据没有存储在我指定的 plist 名称中。
    • NSUserDefaults 不能用于存储在文件中。它是一个系统管理的存储,用于存储首选项。如果您想将数据保存在文件中,请删除所有 NSUserDefault 内容,因为您的代码看起来不错。几个问题: - 当您退出应用程序时,文件还在吗? - 启动应用程序时文件是否消失?
    猜你喜欢
    • 2013-02-11
    • 2018-10-13
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2010-12-18
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多