Loading an NSMatrix created programmatically

Discussion in 'Mac Programming' started by john1620b, Apr 29, 2009.

  1. john1620b macrumors member

    Apr 29, 2009
    I am currently a beginner learning Cocoa, and I've been writing a few test applications trying to figure out some of the things that aren't covered in Hillegass' "Cocoa Programming". My current problem is trying to load an NSMatrix created programmatically. I have an interface set with an outlet connected to an NSMatrix of NSTextFieldCells (declared in the header file as "matrix"), with the following code:

    @implementation AppController
    - (IBAction)loadNewMatrix:(id)sender {
    	NSTextFieldCell* tc = [[NSTextFieldCell alloc] init];
    	matrix = [[NSMatrix alloc] initWithFrame:NSMakeRect(10,10,200,200)
    	[matrix setNeedsDisplay:YES];
    	[tc release];
    	int x = [matrix frame].origin.x;
    	int y = [matrix frame].origin.y;
    	int w = [matrix frame].size.width;
    	int h = [matrix frame].size.height;
    	NSLog(@"%d %d %d %d", x, y, w, h);
    The values according to the log are correct for the new matrix, but the interface doesn't change. Is there a different way to load the new matrix other than -setNeedsDisplay? Or am I going about this all wrong? Any help is greatly appreciated.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    When you setup an IBOutlet and connect it in the nib, what's really going on is the nib-loading process creates that control that you setup in the nib when the nib is loaded and assigns it to your outlet. It's basically a shortcut for programmatically creating the control yourself as you do above. In your code, you are recreating the matrix again, which is unnecessary since you already have the outlet setup. If you want to create it in code, remove the IBOutlet part (but still declare your matrix) and then add the matrix to your window. Something like:
    [[window contentView] addSubview:matrix];
  3. john1620b thread starter macrumors member

    Apr 29, 2009
    Thanks! That worked. In your opinion, if I'm loading a new matrix whenever the "New" menu option is chosen, is it better to create a new matrix programmatically, or have it set it up in IB and modify it when "New" is chosen?
  4. kainjow Moderator emeritus


    Jun 15, 2000
    I would use a nib whenever you can, since it's much easier to modify a control in IB and reduces the amount of code you have to touch.
  5. john1620b thread starter macrumors member

    Apr 29, 2009
    That's what I was hoping you'd say. :) Thanks for the advice, I appreciate it.

Share This Page