2016年5月10日 星期二

plist儲存資料



如何利用plist儲存資料?

做了一個簡單的測試demo在github上:https://github.com/web8246/TestPlist.git






教學已經很多前輩有介紹了,

這邊主要是測試一些不太有人說的功能,例如刪除,和儲存資料類別物件,


appdelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //mylist這個檔案複製到documents底下,這樣在沙盒內儲存
    
    NSFileManager *manager = [[NSFileManager alloc] init];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"plist"];
    NSString *copy = [NSString stringWithFormat:@"%@/Documents/myList.plist",NSHomeDirectory()];
    
    if (![manager fileExistsAtPath:copy]) {
        [manager copyItemAtPath:path toPath:copy error:nil];
    }
    
    return YES;

}

另外在viewcontroller裡面:


- (void)viewDidLoad {
    [super viewDidLoad];
    listDict = [NSMutableDictionary new];
    date1 = [NSMutableDictionary new];
    addItemDic = [NSMutableDictionary new];
    
    // Do any additional setup after loading the view, typically from a nib.
    
    //先取得已經複製好的路徑
    NSString *path = [NSString stringWithFormat:@"%@/Documents/myList.plist",NSHomeDirectory()];
    //read
    listDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    date1 = [listDict objectForKey:@"date1"];
    NSString *major= date1[major];
    NSLog(@"major: %@",major);
    
    //write
    NSLog(@"listDic: %@",listDict);
    
    
}
- (IBAction)addBtnAction:(id)sender {
    
    NSString *path = [NSString stringWithFormat:@"%@/Documents/myList.plist",NSHomeDirectory()];
    [date1 setValue:@"898" forKey:@"major"];
    [date1 setValue:@"ggf" forKey:@"minor"];
    //plist檔案,沒有設置這個key,但是也可以動態加入,讓他存入,刪除也是一樣,都是依照keyvalue
    [date1 setValue:@"ooj" forKey:@"klo"];
    //展示包入Singleton資料物件
    MyItem *item = [MyItem new];
    item.stringA = @"ppokok";
    NSMutableDictionary *newDic = [NSMutableDictionary new];
    [newDic setObject:item forKey:@"kkk"];
    [date1 setObject:newDic forKey:@"newDic"];
    
    
    [listDict writeToFile:path atomically:YES];
    NSLog(@"listDic: %@",listDict);
    
    
}

沒有留言:

張貼留言