PDA

View Full Version : Objective-C error message




uaecasher
Sep 23, 2009, 08:07 AM
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):



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


}


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




@end




implementation file (rec.m) :




//
// 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



#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:



[myRect setWidth:5 andHeight:8];



robbieduncan
Sep 23, 2009, 08:45 AM
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).

iMasterWeb
Sep 23, 2009, 05:04 PM
You might want to READ THE WHOLE PAGE on page 162. He tells you that you need to add a method.

uaecasher
Sep 24, 2009, 06:57 AM
"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

gnasher729
Sep 24, 2009, 08:06 AM
"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.