How to upload and store files in Cocoa with Core Data?

后端 未结 3 429
盖世英雄少女心
盖世英雄少女心 2021-01-15 16:55

I have an app which I would like to be able to upload files to. I could imagine serializing the data, putting that into an array, then serializing the array and putting that

3条回答
  •  再見小時候
    2021-01-15 17:21

    Core Data allows you to set an option for external storage of attributes and IT will then decide whether to store the object in an external file.

    So you would create an attribute called fileData (binary) and in your subclass use NSData and then simply set the file.fileData = yourFileData and Core Data will decide where to store it.

    No need to track the URL yourself. Don't forget to store some kind of identifier (file name) to allow you to retrieve the file you want.

    EDIT

    BTW if you just want to store an image of attributed string then it might be better to use a transformable attribute. Transformable is useful if you want automatic transformation to NSImage, UIImage or NSAttributedString (or some other archivable object).

    set the file like this

    NSData * data = [NSData dataWithContentsOfURL:...];
    file.fileData = data;
    

    To write the data to a file use

    bool result = [file.fileData writeToURL:atomically:];
    

提交回复
热议问题