Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

john1620b

macrumors member
Original poster
Apr 29, 2009
77
0
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:

Code:
@implementation AppController
- (IBAction)loadNewMatrix:(id)sender {
	NSTextFieldCell* tc = [[NSTextFieldCell alloc] init];
	matrix = [[NSMatrix alloc] initWithFrame:NSMakeRect(10,10,200,200)
					    mode:NSListModeMatrix
				       prototype:tc
				    numberOfRows:4
				 numberOfColumns:4];
	[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.
 
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:
Code:
[[window contentView] addSubview:matrix];
 
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?
 
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.
 
That's what I was hoping you'd say. :) Thanks for the advice, I appreciate it.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.