How to store an image in Core Data?

后端 未结 3 1965
暖寄归人
暖寄归人 2021-02-03 14:52

Just a guess: I make an attribute and make it\'s type \"binary\". But in the end, how would I use that? I guess there is an NSData behind the scenes? So that attribute actually

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 15:14

    This question has been asked a number of times and the answer is a bit more complex.

    When it comes to binary data you should determine how to store it based on the expected size of data you are going to be working with. The rule is:

    • Less than 100K;store as a binary property in your main table
    • Less than 1M; store as a binary property in a ancillary table to avoid over fetching
    • Greater than 1M; store on disk and store its file path in the Core Data table.

    In addition, when you are storing images, it is recommended to store them in a standard format such as JPG or PNG. By using the transformable property type you can actually have your subclass give the appearance of accessing the UIImage class when the actual store is a PNG representation. I go into this in detail in the bog post on Cocoa Is My Girlfriend.

    Update

    The reason behind storing > 1M binary data on disk is because of the cache. The NSPersistentStoreCoordinator will keep a cache of data so that when your app asks for the "next" object it doesn't need to go back out to disk. This cache works really well. However it is small, very small on iOS. If you pull in a big piece of binary data you can easily blow out that entire cache and your entire app suffers greatly.

提交回复
热议问题