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

uaecasher

macrumors 65816
Original poster
Jan 29, 2009
1,289
0
Stillwater, OK
hello, I'm learning Objective-C from the book "Programming in Objective-C 2.0".

Now i don't know if this is intentional or not but this book got hell of typos, so I'm in the inheritance chapter and trying to run this example but i keep getting this error message:

'Rectangle' may not respond to "-setWidth:andHeight:'

here is my code:

header file (Rectangle.h):

Code:
@interface Rectangle: NSObject
{
	int width; 
	int height;
	
	
}


@property int width, height;
-(int) area;
-(int) perimeter;




@end


implementation file (rec.m) :


Code:
//
//  rec.m
//  inher
//
//  Created by Fahad Ali on 9/22/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//


#import "Rectangle.h" 


@implementation Rectangle

@synthesize width, height;

-(void) setWidth: (int) w andHeight: (int) h;

{
	
	width = w;
	height = h;
}


-(int) area
{
	return width * height;
}

-(int) perimeter
{
	return (width + height) * 2;
}

@end

main.m

Code:
#import "Rectangle.h"
#import <stdio.h>

int main (int argc, char *argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	Rectangle *myRect = [[Rectangle alloc] init];
	
	[myRect setWidth:5 andHeight:8];
	
	NSLog (@"w = %i, h = %i", 
		   myRect.width, myRect.height);

	NSLog (@"Area = %i, Perimeter = %i", 
		   [myRect area], [myRect perimeter]);

	
	[myRect release];
	[pool drain]; 
	
	return 0;
}


the error appears at:

Code:
	[myRect setWidth:5 andHeight:8];
 
You need to declare the method in the interface file if you are going to call it from outside the class (and not get these warnings).
 
You might want to READ THE WHOLE PAGE on page 162. He tells you that you need to add a method.
 
"Assume that you typed this new class declaration into a file called Rectangle.h" what does he mean by this :p?

edit:

i pasted the method in interface:

-(void) setWidth: (int) w andHeight: (int) h;


and it works now but it i don't know why i have to do this :p
 
"Assume that you typed this new class declaration into a file called Rectangle.h" what does he mean by this :p?

edit:

i pasted the method in interface:

-(void) setWidth: (int) w andHeight: (int) h;


and it works now but it i don't know why i have to do this :p

Because whoever is using the method only reads the header file and not the implementation file. So at the point where you used the method, the compiler didn't have any idea that this method actually exists.

You can add methods in your implementation only, but then they are not supposed to be called from outside that implementation as you did. Usually you get that warning because you spelt the name of a method wrong; you get a warning at compile time and your code will crash at runtime.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.