How to save an NSView without it's instance variables being overwritten by initWithFrame:?

181 Views Asked by At

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 ?

1

There are 1 best solutions below

2
On

This portion of your code doesn't make sense...

@implementation Tragic {
NSColor *color;

}

You do not declare instance variables in the implementation (".m") file. You do that in the interface (".h") file. The .m file should not have those brackets around the implementation statement either.

You can create the color variable in the .m file, but it will not be an "instance" variable accessible from other classes and if you do it it shouldn't be within any brackets.