ios中也有沙盒的概念,就是本程序只能操作本程序中的沙盒部分的东西,如下图:


在哪里放APP文件呢,apple说是放在Documents

Where You Should Put Your App’s Files

To prevent the syncing and backup processes on iOS devices from taking a long time,be selective about where you place files. Apps that store large files can slow down the process of backing up to iTunes or iCloud. These apps can also consume a large amount of a user's available storage,which may encourage the user to delete the app or disable backup of that app's data to iCloud. With this in mind,you should store app data according to the following guidelines:

  • Put user data inDocuments/. User data generally includes any files you might want to expose to the user—anything you might want the user to create,import,delete or edit. For a drawing app,user data includes any graphic files the user might create. For a text editor,it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.

  • Put app-created support files in theLibrary/Application support/directory. In general,this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files,configuration files,templates and modified versions of resources loaded from the app bundle.

  • Remember that files inDocuments/andApplication Support/are backed up by default. You can exclude files from the backup by calling-[NSURL setResourceValue:forKey:error:]using theNSURLIsExcludedFromBackupKeykey. Any file that can be re-created or downloaded must be excluded from the backup. This is particularly important for large media files. If your application downloads video or audio files,make sure they are not included in the backup.

  • Put temporary data in thetmp/directory. Temporary data comprises any data that you do not need to persist for an extended period of time. Remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device. The system will periodically purge these files when your app is not running; therefore,you cannot rely on these files persisting after your app terminates.

  • Put data cache files in theLibrary/Caches/directory. Cache data can be used for any data that needs to persist longer than temporary data,but not as long as a support file. Generally speaking,the application does not require cache data to operate properly,but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient,downloadable content. Note that the system may delete theCaches/directory to free up disk space,so your app must be able to re-create or download these files as needed.

我在虚拟机上打印出来就是这个路径:

/Users/Ys/Library/Developer/CoreSimulator/Devices/$(code)/data/Containers/Data/Application/$(code)/Documents

翻译好麻烦,不翻译了

// refer to:

// 1https://developer.apple.com/library/prerelease/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW1

// 2https://developer.apple.com/library/prerelease/content/documentation/Cocoa/Conceptual/Strings/Articles/readingFiles.html#//apple_ref/doc/uid/TP40003459-SW1

做了一点简单的实现:

protocol AbstractFile{
    func read(file :String) -> String
    func write(file :String,contents :String) -> Bool
    func del(file :String) -> Bool
    func list() -> [String]
}

//  Created by Yeshen on 15/7/9.
//  copyright (c) 2015年 Landow. All rights reserved.
//

import Foundation

class File :AbstractFile{
    let GoblePath: String = "Documents/"
    var Folder: String?
    
    init(folde: String){
        if let dirs : [String] = NSSearchPathForDirectoriesInDomains(
            NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask,true) as [String] {
                if(dirs.count > 0){
                    Folder = (dirs[0] as Nsstring).stringByAppendingPathComponent(folde)
                    do {
                        try NSFileManager.defaultManager().createDirectoryAtPath(GoblePath,withIntermediateDirectories: true,attributes: nil)
                    } catch _ {
                    }
                }
        }
    }
    
    func read(file :String) -> String {
        if let path = Folder?.appendingPathComponent(file){
            if let contents = try? String(contentsOfFile: path,encoding: NSUTF8StringEncoding){
                return contents
            }
        }
        return Strings.empty
    }
    
    func write(file :String,contents :String) -> Bool{
        if let path = Folder?.appendingPathComponent(file){
            var error: NSError?
            do {
                try contents.writetoFile(path,atomically: false,encoding: NSUTF8StringEncoding)
            } catch let error1 as NSError {
                error = error1
            }
            return error == nil
        }
        return false
    }
    
    func del(file :String) -> Bool{
        if let path = Folder?.appendingPathComponent(file){
            var error: NSError?
            do {
                try NSFileManager.defaultManager().removeItemAtPath(path)
            } catch let error1 as NSError {
                error = error1
            }
            return error == nil
        }
        return false
    }
    
    func list() -> [String]{
        var files:[String] = Array<String>()
        if let path = Folder{
            if let list = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path){
                let array = NSArray(array: list)
                for item in array{
                    files.append(item.description)
                }
            }
        }
        return files
    }
    
}

    func appendingPathComponent(path:String) -> String{
        return (self as Nsstring).stringByAppendingPathComponent(path)
    }

简单的调用测试如下:

        let file = File(folde: Consts.file.con)
        print(file.write(IO.N.CurTime,contents: Time.getNow().description))
        print(file.read(IO.N.CurTime))
        print(file.del(IO.N.CurTime))
        print(file.list())

log:

true

1466668253.0

true

[]

swift 文件缓存的更多相关文章

  1. HTML5 WebSocket实现点对点聊天的示例代码

    这篇文章主要介绍了HTML5 WebSocket实现点对点聊天的示例代码的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

  3. ios – 在Swift中将输入字段字符串转换为Int

    所以我非常擅长制作APP广告Swift,我试图在文本字段中做一些非常简单的输入,取值,然后将它们用作Int进行某些计算.但是’vardistance’有些东西不正确它是导致错误的最后一行代码.它说致命错误:无法解开Optional.None解决方法在你的例子中,距离是一个Int?否则称为可选的Int..toInt()返回Int?因为从String到Int的转换可能失败.请参阅以下示例:

  4. 如何在iOS中检测文本(字符串)语言?

    例如,给定以下字符串:我想检测每个声明的字符串中使用的语言.让我们假设已实现函数的签名是:如果没有检测到语言,则返回可选字符串.因此,适当的结果将是:有一个简单的方法来实现它吗?

  5. xamarin – 崩溃在AccountStore.Create().保存(e.Account,“);

    在Xamarin.Forms示例TodoAwsAuth中https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/成功登录后,在aOnAuthenticationCompleted事件中,应用程序在尝试保存到Xamarin.Auth时崩溃错误说不能对钥匙串说期待着寻求帮助.解决方法看看你

  6. ios – 将视频分享到Facebook

    我正在编写一个简单的测试应用程序,用于将视频从iOS上传到Facebook.由于FacebookSDK的所有文档都在Objective-C中,因此我发现很难在线找到有关如何使用Swift执行此操作的示例/教程.到目前为止我有这个在我的UI上放置一个共享按钮,但它看起来已禁用,从我读到的这是因为没有内容设置,但我看不出这是怎么可能的.我的getVideoURL()函数返回一个NSURL,它肯定包含视

  7. xcode – 错误“线程1:断点2.1”

    我正在研究RESTAPI管理器.这是一个错误,我无法解决它.我得到的错误在下面突出显示.当我打电话给这个班级获取资源时:我评论的线打印:Thread1:breakpoint2.1我需要修复错误的建议.任何建议都非常感谢解决方法您可能在不注意的情况下意外设置了断点.单击并拖动代表断路器外部断点的蓝色刻度线以将其擦除.

  8. ios – 更改导航栏标题swift中的字符间距

    类型的值有人可以帮我这个或建议一种不同的方式来改变swift中导航栏标题中的字符间距吗?解决方法您无法直接设置属性字符串.你可以通过替换titleView来做一个技巧

  9. ios – 如何从变量访问属性或方法?

    是否可以使用变量作为Swift中方法或属性的名称来访问方法或属性?在PHP中,您可以使用$object->{$variable}.例如编辑:这是我正在使用的实际代码:解决方法你可以做到,但不能使用“纯粹的”Swift.Swift的重点是防止这种危险的动态属性访问.你必须使用Cocoa的Key-ValueCoding功能:非常方便,它完全穿过你要穿过的字符串到属性名称的桥,但要注意:这里是龙.

  10. ios – 如果我将自动释放的对象桥接到Core Foundation,我必须使用__bridge或__bridge_retained吗?

    ARC迁移工具遇到了这个问题:特别是,它不确定它是否应该执行__bridge或__bridge_retained.而我也是.-fileURLWithPath返回一个自动释放的对象,在这个地方我不是fileURL的所有者.但与此同时,该对象的保留计数至少为1.我敢打赌,这只能用__bridge来完成.解决方法您只想为此使用常规__bridge强制转换.仅当您想要管理强制转换CF对象的生命周期时,才会使用__bridge_retained.例如:所以__bridge_retained确实告诉编译器你有一个AR

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部