简体   繁体   中英

Core Data: How do I store a CGImageRef or custom data types?

my iPhone application should store some data persistantly by using Core Data functionality.

Here is a code snippet:

NSManagedObject *entity = [NSEntityDescription insertNewObjectForEntityForName:@"anEntity" inManagedObjectContext:self.managedObjectContext];

// ...
CGContextRef context;
// ...
[entity setContext:context];
NSError *error;
[self.managedObjectContext save:&error];
// ...

My data model defines context 's type as "transformable". Is this right? At build time I get the following warning:

warning: passing argument 1 of 'setContext:' from incompatible pointer type

How can you store a CGContextRef or in general a custom data type with Core Data? Does this require the implementation of a Encoder/Decoder?

Thank you, Norbert

You will need to serialize the image to an NSData (or CFData) instance first. Look at CGImageDestinationCreateWithData to do this.

In this answer , I provide code for an NSValueTransformer that lets you save UIImages into a transformable attribute in Core Data. You could do something similar for the drawn image in your context. If you need to preserve the vector elements, you could draw to a PDF context and save the data for that representation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM