你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS_swift文件系統

IOS_swift文件系統

編輯:IOS開發綜合
    func files(){
        //應用根目錄
        let dir = NSHomeDirectory();
        NSLog("dir = \(dir)")
        
        // 文檔目錄
        let doc = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        NSLog("doc = \(doc)")
        
        // library目錄
        let library = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
        NSLog("doc = \(library)")
        
        //判斷目錄是否存在
        let manager = NSFileManager.defaultManager()
        let myDir = "\(doc)/my"
        let isExist = manager.fileExistsAtPath(myDir)
        if(isExist){
            NSLog("存在my文件夾")
        }else{
            NSLog("不存在my文件夾!")
            //創建文件夾
            do{
                try manager.createDirectoryAtPath(myDir, withIntermediateDirectories: true, attributes: nil)
            }catch{
            }
        }
        
        //判斷文件是否存在
        let myTxt = "\(doc)/my.txt"
        let isExistMyTxt = manager.fileExistsAtPath(myTxt)
        if(isExistMyTxt){
            NSLog("存在my.txt")
        }else{
            NSLog("不存在my.txt")
            //創建文件
            manager.createFileAtPath(myTxt, contents: nil, attributes: nil)
        }
        
        // 用戶首選項
        let userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject("2012", forKey: "time")
        userDefault.synchronize()
        
        let time = userDefault.stringForKey("time")
        NSLog("time = \(time!)")
        
        //保存文件
        let arr:NSArray = ["11","33","22"]
        arr.writeToFile(myTxt, atomically: true)
        
        let content = NSArray(contentsOfFile: myTxt)!
        print(content)
        
        //對象保存
        let stuPlist = "\(doc)/stu.plist"
        let stu = Student(name: "zhangsan", age: 20)
        NSKeyedArchiver.archiveRootObject(stu, toFile: stuPlist)
        
        let stu2 = NSKeyedUnarchiver.unarchiveObjectWithFile(stuPlist) as? Student
        if stu2 != nil {
            print("name = \(stu2!.name), age = \(stu2!.age)")
        }
    }

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved