swift 数组和字典保存到文件中

前端之家收集整理的这篇文章主要介绍了swift 数组和字典保存到文件中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.保存数组到文件

 //MARK:1,数组(Array)的存储和读取
    func testSaveArrayPlist() {
        let arry = NSArray(objects: "stev","baidu.com","com","12344","robinson")
        let filePath:String = NSHomeDirectory() + "/Documents/tf.plist"
        arry.writeToFile(filePath,atomically: true)
        
        tfArray = NSArray(contentsOfFile:NSHomeDirectory() + "/Documents/tf.plist")
        
        print(tfArray)
    }


数组打印结果如下:
Optional(<__NSCFArray 0x7dbba000>(
stev,baidu.com,com,12344,robinson
)
)


2.保存字典到文件

func testSaveDicPlist(){
        let  myArray = [
            
            [
                ["name":"小明","url":"google.com"],["name":"张三","url":"tf234.com"],["name":"里斯","url":"csdn.com"]
            ],[
                ["name":"张三","url":"csdn.com"]
            ]
        ]
        
        let filePath:String = NSHomeDirectory() + "/Documents/tfDic.plist"
        NSArray(array: myArray).writeToFile(filePath,atomically: true)
        print(filePath)
        
        tfArray = NSArray(contentsOfFile:NSHomeDirectory() + "/Documents/tfDic.plist")
        
        print(tfArray)
    }

字典打印结果如下:
Optional(<__NSCFArray 0x7aa6f4a0>(
<__NSCFArray 0x7aa6df50>(
{
    name = "\U822a\U54e5";
    url = "hangge.com";
},{
    name = "\U767e\U5ea6";
    url = "baidu.com";
},{
    name = google;
    url = google;
}
),<__NSCFArray 0x7aa70de0>(
{
    name = 163;
    url = "163.com";
},{
    name = google;
    url = "google.com";
}
)

)
)

猜你在找的Swift相关文章