A Cocoa newbie here. I was trying to encode an instance variable inside an NSView to save to a file. But whenever I encode it, it is being overwritten to (null) when the initWithFrame: is being called. Is there a way I can skip this behaviour and load the instance variables on to an unarchived NSView ? Here is the code I have :
#import "Tragic.h"
@implementation Tragic {
NSColor *color;
}
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSLog(@"%@",color);
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
if(!color) {
color = [NSColor greenColor];
}
[color set];
color = [NSColor yellowColor];
NSRectFill([self bounds]);
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
[aCoder encodeObject:color forKey:@"color"];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
color = [aDecoder decodeObjectForKey:@"color"];
}
return self;
}
@end
In the above code, I first set the color to be filled as green and just after the drawRect: method finishes change it to yellow, so the color that gets saved is yellow. But nevertheless, it reverts to null in the initWithFrame: log comment and the I get a green screen again. From the looks of it, the only way seems to be separating data from the view. But if there's a simpler way, can anyone help me ?