IOS和.plists

时间:2013-03-24 22:05:46

标签: ios xcode

我正在为一个高级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。关于如何修复覆盖问题的任何想法?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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.

Property List Programming Guide