Reputation: 2062
I'm working on an OSX app and need to save a custom class's information, so I am trying to index it using NSCoder; however, one of the objects I'm trying to encode/decode in the class is an NSImage, and every time i try to run encodeWithCoder: or initWithCoder: I one of these two error messages:
Warning - attempting to encode NSCGSImageRep
Warning - attempting to decode NSCGSImageRep
Here's my .m:
@implementation Subject
-(id) init{
self = [super init];
if (self) {
self.ad = [[NSApplication sharedApplication] delegate];
self.editViewController = self.ad.editViewController;
self.name = @"";
self.teacher = @"";
self.mainPeriod = 1;
}
return self;
}
-(void) encodeWithCoder: (NSCoder *) coder{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeObject:self.teacher forKey:@"teacher"];
NSNumber *periodNumBox = [NSNumber numberWithInt:self.mainPeriod];
[coder encodeObject:periodNumBox forKey:@"mainPeriod"];
[coder encodeObject:self.image forKey:@"image"];
}
-(id) initWithCoder: (NSCoder *) coder{
self.name = [coder decodeObjectForKey:@"name"];
self.teacher = [coder decodeObjectForKey:@"teacher"];
NSNumber *periodNumBox = [coder decodeObjectForKey:@"mainPeriod"];
self.mainPeriod = (int)[periodNumBox integerValue];
self.image = [coder decodeObjectForKey:@"image"];
return self;
}
@end
and my .h:
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "EditViewController.h"
@class EditViewController;
@interface Subject : NSObject
@property (weak) AppDelegate *ad;
@property EditViewController *editViewController;
@property NSImage *image;
@property NSString *name;
@property NSString *teacher;
@property int mainPeriod;
@end
Upvotes: 0
Views: 678
Reputation: 535411
This isn't quite what you're asking, but it might be a solution worth considering: don't. If the image is guaranteed to exist elsewhere at decode time, all you need to archive is the name or other reference to the image. If the image is not guaranteed to exist elsewhere at decode time, then save it to disk where it will be guaranteed to exist, and archive the name or other reference to it.
Please see also my answer here on how to transform an image to NSData:
https://stackoverflow.com/a/15694549/341994
NSData can be written directly to a file on disk. Of course, since an NSData object is archivable, you could now put it in an archive; it will work with encoding and decoding. But I would still argue that you should prefer not to do so.
Upvotes: 3