Search code examples
objective-ccocoansviewsubviews

NSView and loading subviews on the fly


To get a sense of what I'm doing without posting pages of code... I have an NSOperation that I'm using to process files as they are added to a folder. In that NSOperation I'm using the NSNotificationCenter to send notifications to an NSView whenever a new job is started. The idea is, that I want to add a new subview to give me some information about the job that just started. The problem is I can't seem to get new subviews to draw. Here is what I have right now.

- (void)drawRect:(NSRect)dirtyRect
{
    NSLog(@"Draw Count %i", [jobViewArray count]);
    int i = 0;
    while (i < [jobViewArray count]) {
        [self addSubview:[jobViewArray objectAtIndex:i]];
    }    

}

and then further down:

-(void) newJobNotification: (NSNotification *) notification
{
    if (!jobViewArray)
            jobViewArray = [[NSMutableArray alloc] init];
    ++jobCount;
    NSRect rect;
    rect.size.width = 832;
    rect.size.height = 120;
    NSPoint point = { 0, ((jobCount * 120) - 120) };
    rect.origin = point;
    ProgressView *newJob = [[ProgressView alloc] initWithFrame:rect];

    [jobViewArray addObject:newJob];    
    NSLog(@"Notice Count %i", [jobViewArray count]);

    }

}

When I use my app to add a job, the notification is properly received by my NSView, the subview is properly added to the jobViewArray, but then when drawRect: gets called again my jobViewArray is empty. It's the first time I've tried to do something like this so I'm probably doing something completely wrong here... I guess that goes with out saying since it doesn't work huh?


Solution

  • You shouldn't be adding the subview to the view in drawRect:. When you receive the notification you should add the subviews there because the second time the notification comes around, you're going to add 2 subviews, then the next time 3 subviews and so one.

    If you add the subview in the notification then you'll not need to mess around with the array.