0

我正在为高级 Capstone 开发应用程序,并且是第一次使用 .plist。到目前为止,我的 .h 中有什么:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
-(NSString *)dataFilePath;
-(IBAction) readPlist:(id)sender;
-(IBAction) writePlist:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *textBox;

@end

在我的 .m 中,我有:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSString *) dataFilePath
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES );
    NSString *documentDirectory = [path objectAtIndex:0];
    return [documentDirectory stringByAppendingPathComponent:@"JoesData.plist"];
}
- (IBAction)readPlist:(id)sender
{
    NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        NSLog(@"%@\n",array);
        NSLog(@"%@\n", filePath);
    }
}
- (IBAction)writePlist:(id)sender {
    NSString *string = _textBox.text;
    NSMutableArray *anArray = [[NSMutableArray alloc] init];

    [anArray addObject:string];
    [anArray writeToFile:[self dataFilePath] atomically:YES];
}
@end

所以它的作用是根据我在故事板中设置的文本框中的内容创建一个 .plist。我的问题是它可以很好地读写它,但它不会保留输入到文本框中的内容的运行列表。相反,它只是覆盖了以前的 .plist。关于如何解决覆盖问题的任何想法?

4

2 回答 2

1

将 plist 读入内存,制作数组的可变副本,然后将对象添加到该数组中,而不是NSMutableArray每次都创建一个新对象。

于 2013-03-24T22:10:40.923 回答
0

另一种选择是执行以下操作。

To read the property-list data back into your program, first initialize an allocated NSData object by invoking initWithContentsOfFile: or initWithContentsOfURL: or call a corresponding class factory method such as dataWithContentsOfFile:. Then call the propertyListFromData:mutabilityOption:format:errorDescription: class method of NSPropertyListSerialization, passing in the data object.

属性列表编程指南

于 2013-03-24T22:27:31.623 回答