0

私はシニアキャップストーン用のアプリに取り組んでおり、.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

NSMutableArray毎回新しいものを作成するのではなく、plist をメモリに読み込み、配列の変更可能なコピーを作成し、その配列にオブジェクトを追加します。

于 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 に答える