你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> 數據持久化之plist存儲

數據持久化之plist存儲

編輯:關於IOS

**plist文件其實就是XML文檔,只是後綴名為plist。

如果對象是NSString、NSDictionary、NSArray、NSData、NSNumber等類型,就可以使用writeToFile:atomically:方法直接將對象寫到屬性列表文件中
**

關於plist文件的寫入

<code class="hljs objectivec has-numbering">- (<span class="hljs-keyword">void</span>)saveArray
{
    <span class="hljs-comment">// 1.獲得沙盒根路徑</span>
    <span class="hljs-built_in">NSString</span> *home = NSHomeDirectory();

    <span class="hljs-comment">// 2.document路徑</span>
    <span class="hljs-built_in">NSString</span> *docPath = [home stringByAppendingPathComponent:@<span class="hljs-string">"Documents"</span>];

    <span class="hljs-comment">// 3.新建數據</span>
    <span class="hljs-built_in">NSArray</span> *data = @[@<span class="hljs-string">"jack"</span>, @<span class="hljs-number">10</span>, @<span class="hljs-string">"ffdsf"</span>];


    <span class="hljs-built_in">NSString</span> *filepath = [docPath stringByAppendingPathComponent:@<span class="hljs-string">"data.plist"</span>];


    [data writeToFile:filepath atomically:<span class="hljs-literal">YES</span>];
}</code>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

關於plist文件的讀取

<code class="hljs objectivec has-numbering">- (<span class="hljs-keyword">IBAction</span>)read {
    <span class="hljs-comment">// 1.獲得沙盒根路徑</span>
    <span class="hljs-built_in">NSString</span> *home = NSHomeDirectory();

    <span class="hljs-comment">// 2.document路徑</span>
    <span class="hljs-built_in">NSString</span> *docPath = [home stringByAppendingPathComponent:@<span class="hljs-string">"Documents"</span>];

    <span class="hljs-comment">// 3.文件路徑</span>
    <span class="hljs-built_in">NSString</span> *filepath = [docPath stringByAppendingPathComponent:@<span class="hljs-string">"data.plist"</span>];

    <span class="hljs-comment">// 4.讀取數據</span>
    <span class="hljs-built_in">NSArray</span> *data = [<span class="hljs-built_in">NSArray</span> arrayWithContentsOfFile:filepath];
    <span class="hljs-built_in">NSLog</span>(@<span class="hljs-string">"%@"</span>, data);
}</code>
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved