1. 程式人生 > >object-c 檔案基本讀寫

object-c 檔案基本讀寫

    NSString *path = @"/Users/beyondsoft/Desktop/file.plist";
        NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"one", @"1", @"2", @"two", @"three", @"5", nil];
        [dict writeToFile:path atomically:YES];
        [dict release];
        NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:path];
        NSLog(@"%@", dict);
        [dict release];
        
        NSArray *array = [[NSArray alloc]initWithObjects:@"one", @"two", @"4", @"6", nil];
        [array writeToFile:path atomically:YES];
        [array release];

        // 寫入檔案 歸檔檔案,不同格式讀寫。
        NSString *path = @"/Users/beyondsoft/Desktop/file.plist";
        NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"one", @"1", @"2", @"two", @"three", @"5", nil];   
        NSArray *array = [[NSArray alloc]initWithObjects:@"one", @"two", @"4", @"6", nil];
        
        NSMutableData *data = [[NSMutableData alloc]init];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
        [archiver encodeObject:array forKey:@"array"];
        [archiver encodeObject:dict forKey:@"dic"];
        [archiver finishEncoding];
        [data writeToFile:path atomically:YES];
        [array release];
        [dict release];
        [data release];
        [archiver release];


        //讀取檔案
        NSString *path = @"/Users/beyondsoft/Desktop/file.plist";
        NSData *data1 = [[NSData alloc]initWithContentsOfFile:path];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];
        NSArray *array1 = [unarchiver decodeObjectForKey:@"array"];
        NSLog(@"%@", array1);
        NSDictionary *dict = [unarchiver decodeObjectForKey:@"dic"];
        NSLog(@"%@", dict);
        [data1 release];
        [unarchiver release];

對類進行歸檔
        //對一個類進行歸檔,類要實現NScodeing協議,並且要實現相應方法encodeWithCode, initWithCoder;
        Dog *dog = [[Dog alloc]init];
        dog.ID = 20;
        NSString *path = @"/Users/beyondsoft/Desktop/file.plist";
        NSDat
  //對一個類進行歸檔,類要實現NScodeing協議,並且要實現相應方法encodeWithCode, initWithCoder;
        Dog *dog = [[Dog alloc]init];
        dog.ID = 20;
        NSString *path = @"/Users/beyondsoft/Desktop/file.txt";
        NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:dog];
        [data1 writeToFile:path atomically:YES];
        [dog release];
        
        // read
        NSData *data2 = [NSData dataWithContentsOfFile:path];
        Dog *dog2  =[NSKeyedUnarchiver unarchiveObjectWithData:data2];
        NSLog(@"%ld, %ld", dog.ID, dog2.ID);

a *data1 = [NSKeyedArchiver archivedDataWithRootObject:dog]; [data1 writeToFile:path atomically:YES]; [dog release];