Just a Computer Graphics Studio & My Life

一直想知道如何在Objective C將資料寫入檔案,沒想到只是一個方法writeToFile就可以完成!比較讓我訝異的是,Objective C不像C語言,是寫到txt檔,反而是寫成xml檔

哈~突然讓我想到我們系上那個教xml的教授,我一直不敢去上他的課,害怕浪費時間和金錢,只是為了那三個學分~為什麼?我想要學到東西!

在此我以NSArray和NSDictionary示範,其他資料形態物件還有如:

  • NSArray
  • NSMutableArray
  • NSDictionary
  • NSMutableDictionary
  • NSData
  • NSMutableData
  • NSString
  • NSMutableString
  • NSNumber
  • NSDate

程式碼:

//
//  main.m
//  HappyMan's Program - writeToFile
//  Xcode 4.5
//  Created by ShengWen on 12/10/30.
//  Copyright (c) 2012年 ShengWen. All rights reserved.
//  https://cg2010studio.wordpress.com/

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSArray *array = @[@"HappyMan", @"WaterMan", @"BrightMan"];
    NSArray *array2array = @[array];
    NSDictionary *dictionary = @{@"array": array, @"array2array": array2array, @"word1": @"Happy", @"word2": @"Man", @"word3": @"Studio"};
    NSDictionary *dictionary2dictionary = @{@"dictionary": dictionary};

    // 得到documents directory的路徑
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if([paths count] > 0)
    {
        // Array的保存路徑
        NSString *arrayPath = [[paths objectAtIndex: 0] stringByAppendingPathComponent: @"array.txt"];
        NSString *array2arrayPath = [[paths objectAtIndex: 0] stringByAppendingPathComponent: @"array2array.txt"];

        // dictionary的保存路徑
        NSString *dictPath = [[paths objectAtIndex: 0] stringByAppendingPathComponent : @"dict.txt"];
        NSString *dict2dictPath = [[paths objectAtIndex: 0] stringByAppendingPathComponent : @"dict2dict.txt"];

        // 寫到檔案
        [array writeToFile: arrayPath atomically: YES];
        [array2array writeToFile: array2arrayPath atomically: YES];
        [dictionary writeToFile: dictPath atomically: YES];
        [dictionary2dictionary writeToFile: dict2dictPath atomically: YES];

        // 讀取檔案
        NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile: arrayPath];
        NSArray *array2arrayFromFile = [NSArray arrayWithContentsOfFile: array2arrayPath];
        NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile: dictPath];
        NSDictionary *dict2dictFromFile = [NSDictionary dictionaryWithContentsOfFile: dict2dictPath];

        // 列印
        for(NSString *element in arrayFromFile)
            NSLog (@"Array: %@", element);
        for(NSString *element in array2arrayFromFile)
            NSLog (@"Array2Array: %@", element);

        for(NSString *key in dictFromFile)
            NSLog (@"Dictionary: %@: %@", key, [dictionary valueForKey: key]);
        for(NSString *key in dict2dictFromFile)
            NSLog (@"Dictionary2Dictionary: %@: %@", key, [dictionary2dictionary valueForKey: key]);
    }
    return 0;
}

執行結果:

2012-10-30 01:23:49.853 HappyMan’s First Program[3730:403] Array: HappyMan

2012-10-30 01:23:49.854 HappyMan’s First Program[3730:403] Array: WaterMan

2012-10-30 01:23:49.855 HappyMan’s First Program[3730:403] Array: BrightMan

2012-10-30 01:23:49.855 HappyMan’s First Program[3730:403] Array2Array: (

    HappyMan,

    WaterMan,

    BrightMan

)

2012-10-30 01:23:49.856 HappyMan’s First Program[3730:403] Dictionary: word1: Happy

2012-10-30 01:23:49.857 HappyMan’s First Program[3730:403] Dictionary: word3: Studio

2012-10-30 01:23:49.857 HappyMan’s First Program[3730:403] Dictionary: array2array: (

        (

        HappyMan,

        WaterMan,

        BrightMan

    )

)

2012-10-30 01:23:49.858 HappyMan’s First Program[3730:403] Dictionary: array: (

    HappyMan,

    WaterMan,

    BrightMan

)

2012-10-30 01:23:49.859 HappyMan’s First Program[3730:403] Dictionary: word2: Man

2012-10-30 01:23:49.859 HappyMan’s First Program[3730:403] Dictionary2Dictionary: dictionary: {

    array =     (

        HappyMan,

        WaterMan,

        BrightMan

    );

    array2array =     (

                (

            HappyMan,

            WaterMan,

            BrightMan

        )

    );

    word1 = Happy;

    word2 = Man;

    word3 = Studio;

}

我的範例程式總共產生四個檔案:array.txt、array2array.txt、dict.txt、dict2dict.txt,雖然都儲存為txt檔,但其內容都是xml檔的格式喔!它們都位於/Users/ShengWen/Documents,我們就先以dict2dict.txt內容為例~

檔案內容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>dictionary</key>
	<dict>
		<key>array</key>
		<array>
			<string>HappyMan</string>
			<string>WaterMan</string>
			<string>BrightMan</string>
		</array>
		<key>array2array</key>
		<array>
			<array>
				<string>HappyMan</string>
				<string>WaterMan</string>
				<string>BrightMan</string>
			</array>
		</array>
		<key>word1</key>
		<string>Happy</string>
		<key>word2</key>
		<string>Man</string>
		<key>word3</key>
		<string>Studio</string>
	</dict>
</dict>
</plist>

話說,我一直在iOS上找writeToFile儲存檔案的位置,結果根本找不到……而我這程式碼是在Mac OS上執行,所以能在文件夾中找到檔案~哈!以前Windows寫入檔案我都直接輸出到跟執行檔一樣的資料夾。

參考:將Array、Dictionary等集合類的序列化和反序列化Objective-C Property ListiPhone 開發教學 – 使用 Property List 和 SQLite 處理資料儲存iOS開發23:通過歸檔永久存儲數據

廣告

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: