Chellange: Problem with loading from file


#1

Hello
I built an application to draw ovals on a view. The ovals are saved in a NSMutableArray as an object that I have created with a NSColor variable an a NSBezierPath variable.
When I save the array to a file, all objects are saved.
When I open this file, it unarchives all the objects in this array, but I can’d draw them to the view.
When teh array is unarchived i send the message:

self setNeedsDisplay:YES];

My drawRect: method looks like this:

- (void)drawRect:(NSRect)dirtyRect
{
    NSRect bounds = [self bounds];
    
    // Fill the view with green
    [[NSColor greenColor] set];
    [NSBezierPath fillRect:bounds];
    
     Oval *oval = [[Oval alloc] init];
     
    int red = rand() % 255;
    int green = rand() % 255;
    int blue = rand() % 255;
    NSColor* myColor = [NSColor colorWithCalibratedRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
    
    NSBezierPath *path = [NSBezierPath bezierPathWithOvalInRect:[self currentRect]];
    
    [oval setColor:myColor];
    [oval setPath:path];
    
    
     [array addObject:oval];
    
     myColor = nil;
    
    for (Oval *p in array) {
        [[p color] set];
        [[p path] fill];
    }
    
}

(Oval is the class that i wrote with the two objects)

Oval.h:

//
//  Oval.h
//  OvalFun
//
//  Created by Roger Kreienbühl on 06.03.13.
//  Copyright (c) 2013 Roger Kreienbühl. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Oval : NSObject <NSCoding> {
    NSBezierPath *path;
    NSColor *color;
}

@property (strong) NSBezierPath *path;
@property (strong) NSColor *color;

@end

Oval.m:

//
//  Oval.m
//  OvalFun
//
//  Created by Roger Kreienbühl on 06.03.13.
//  Copyright (c) 2013 Roger Kreienbühl. All rights reserved.
//

#import "Oval.h"

@implementation Oval

@synthesize path;
@synthesize color;

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:path forKey:@"path"];
    [aCoder encodeObject:color forKey:@"color"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        path = [aDecoder decodeObjectForKey:@"path"];
        color = [aDecoder decodeObjectForKey:@"color"];
    }
    return self;
}

@end

What am I doing wrong?


#2

Ok I fount the failure. The array was in my view, but by loading the file, the view isn’t initialized, so I couldn’t set the array.
Now I set the the array in the method awakeFromNib.