2013-03-24 47 views
0

我正在爲一個高級頂點的應用程序,我正在與.plist第一次工作。我至今在我的.h:IOS和.plists

#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。有關如何解決覆蓋問題的任何想法?

回答

1

將plist讀入內存,製作數組的可變副本,並將該對象添加到該數組中,而不是每次都創建一個新的NSMutableArray

+0

你能告訴我?我不太明白你的意思。 – joeBustamante 2013-03-25 15:19:27

+0

@joeBustamante:'NSMutableArray * ary = [[NSArray arrayWithContentsOfFile:[self dataFilePath]] mutableCopy]?:[NSMutableArray array]; [ary addObject:string]; [ary writeToFile:[self dataFilePath] atomically:YES];' – 2013-03-25 18:00:38

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