Use of undeclared identifier: Area and Perimeter of a Rectangle - objective-c

i am new to Objective-C, not entirely sure where I am going wrong here.
I am trying to get the program to print the area and perimeter of a square.
The program is telling me that I am sending an undeclared identifier to the perimeter and area methods
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
{
int width;
int height;
}
-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(int) width;
-(int) height;
-(int) area;
-(int) perimeter;
#end
#implementation Rectangle
-(void) setWidth:(int)w
{
width = w;
}
-(void) setHeight: (int)h
{
height = h;
}
-(int) width
{
return width;
}
-(int) height
{
return height;
}
-(int) area
{
return width*height;
}
-(int) perimeter
{
return (2*width + 2*height);
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
Rectangle *rect1 = [[Rectangle alloc] init];
[rect1 setWidth:2];
[rect1 setHeight:7];
NSLog(#"The perimeter of rect1 is: %i and the area is: %i", area, area);
}
return 0;
}

There's no variable named area, it is a method. Try [rect1 area]; and [rect1 perimeter];, you already created the object and used two methods correctly, you slipped on the area :( Good luck!

Out of curiosity, what learning resources are you using?
I highly recommend Paul Hegarty's iOS dev course from Stanford. All free, and it really guides you through everything (ObjC syntax; iOS SDK etc.)
http://www.stanford.edu/class/cs193p/cgi-bin/drupal/

I changed the line to:
NSLog(#"The perimeter of rect1 is: %i and the area is: %i", [rect1 area], [rect1 perimeter]);
and it gave me the right results, thanks for the help!

Related

Calculation/variable returning as zero

I am setting up a basic geometry class where I define a rectangle and can manipulate the width and height along with calculating the area and perimeter. Everything works and outputs fine, except the perimeter and area variables return as zero. I don't know how to set the variable properly within itself or during the #implementation, so I'm sure it is showing the zero from when the variable is first initialized (before the width and height are set).
I'm inexperienced with OOP and ObjC so I may be missing something simple.
#import <Foundation/Foundation.h>
// #interface setup as required.
#interface Rectangle: NSObject
-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(int) width;
-(int) height;
-(int) area;
-(int) perimeter;
-(void) print;
#end
// #implementation setup for the exercise.
#implementation Rectangle {
int width;
int height;
int perimeter;
int area;
}
// Set the width.
-(void) setWidth: (int) w {
width = w;
}
// Set the height.
-(void) setHeight: (int) h {
height = h;
}
// Calculate the perimeter.
-(int) perimeter {
return (width + height) * 2;
}
// Calculate the area.
-(int) area {
return (width * height);
}
-(void) print {
NSLog(#"The width is now: %i.", width);
NSLog(#"The height is now: %i.", height);
NSLog(#"The perimeter is now: %i.", perimeter);
NSLog(#"The area is now: %i.", area);
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
// Create an instance of Rectangle.
Rectangle *theRectangle;
theRectangle = [Rectangle alloc];
theRectangle = [theRectangle init];
// Use the designed methods.
[theRectangle setWidth: 100];
[theRectangle setHeight: 50];
[theRectangle print];
}
return 0;
}
Short answer:
Call your object methods like this:
[self perimeter];
// as in
NSLog(#"The perimeter is now: %i.", [self perimeter]);
instead of just
perimeter
which accesses the variable with that name, instead of calling the method you've defined.
Longer answer:
There are several things in your code that can be improved:
You should use properties instead of ivars and methods to get and set them. A property declared like this: #property (nonatomic) int width; will give you a getter and a setter, created implicitly by the compiler. So then you can do either of these to set a value:
theRectangle.width = 100;
// is the same as:
[theRectangle setWidth:100];
You can override your getters and setters too. You could also create readonly properties, e.g.
#interface Rectangle: NSObject
#property (nonatomic) int width;
#property (nonatomic) int height;
#property (nonatomic, readonly) int perimeter;
#end
#implementation Rectangle
- (int)perimeter
{
return self.width * self.height * 2;
}
#end

Assistance needed writing simple Objective-C program

I have been struggling along with an online objective-c class for a few weeks now. I'm feeling very stupid..
My latest assignment is to write a program that demonstrates a class named Circle by asking the user for the circle's radius, creating a Circle object, and then reporting the circle's area, diameter, and circumference.
We should have the following member variables:
radius: a double
pi: a double initialized to 3.14159
and the following member functions:
setRadius - a mutator function for the radius variable
getRadius - an accessor function for the radius variable
getArea - returns the area of the circle, which is calculated as: area = pi * radius * radius
getDiameter - returns the diameter of the circle, which is calculated as: diameter = radius * 2
getCircumference - returns the circumference of the circle, which is calculated as: circumference = 2 * pi * radius
The member variables of the class should be set as private.
Here is my program so far:
Main:
int main(int argc, const char * argv[])
{
#autoreleasepool {
int radius;
NSLog(#"Enter the circles radius:");
scanf ("%d", &radius);
}
return 0;
}
Interface:
#import <Foundation/Foundation.h>
//circle class
#interface circle : NSObject
{ #private
-(double) radius;
-(double) pi;
}
#property int setRadius, getRadius;
-(double) getArea;
-(double) getDiameter;
-(double) getCircumcerence;
#end
Implementation:
#import "circle.h"
#implementation circle
#synthesize setRadius, getRadius;
-(double) pi
{
pi = 3.14159;
}
-(double) getArea
{
pi * radius * radius;
}
-(double) getDiameter
{
radius * 2;
}
-(double) getCircumcerence
{
2 * pi * radius;
}
#end
As you can see, I haven't gotten very far. I am confused as how to simply utilize my methods in my main, and am sure I have already made mistakes.
Any advice is appreciated! I really need help, and am short on time.
Also, this may be far-fetched but if anyone could maybe skype with me and help me through it?
Thanks!
As a starting point, you should set up your .h to something more like this:
#interface Circle : NSObject
#property double radius;
#property (readonly) double area;
#property (readonly) double diameter;
#property (readonly) double circumference;
#property (readonly) double pi;
-(id)initWithRadius:(double)r;
+(instancetype)circleWithRadius:(double)r;
#end
This will set up a setter and getter for radius as well as getters for area, diameter, and circumference. It also sets up an init and factory method for your circle which takes a double for the radius.
I will come back and edit in some modifications you need to make to your .m as well as your main file in order to make this work. As a note, at a minimum we'll override the getters for the 3 readonly properties. This will prevent the compiler from creating ivars (instance variables) for these properties (because we can just calculate and return the number we calculation when we call it).
In your .m:
#import Circle.h
#implementation Circle
-(id)initWithRadius:(double)r
{
self = [super init];
if(self) {
self.radius = r;
}
return self;
}
+(instancetype)circleWithRadius:(double)r
{
return [[Circle alloc] initWithRadius:r];
}
-(void)setRadius:(double)r //This method is automatically created by #property
{ //include any verification logic (make sure r>0 etc), then...
self.radius = r;
}
//we don't really need to override the radius getter
-(double)pi
{
return 3.14159; //or however much accuracy you want
}
-(double)area
{
return (self.pi * self.radius * self.radius);
}
-(double)diameter
{
return (2.0 * self.radius);
}
-(double)circumference
{
return (self.diameter * self.pi);
}
In main, you use this Circle class in just the same way you use any other object in Objective-C (think about NSString, NSArray, etc).
int main(int argc, const char * argv[])
{
#autoreleasepool {
double radius;
NSLog(#"Enter the circles radius:");
scanf ("%lf", &radius);
Circle *myCircle = [Circle circleWithRadius:radius]; //the factory method we set up
NSLog(#"myCircle radius: %lf", myCircle.radius);
NSLog(#"myCircle area: %lf", myCircle.area);
NSLog(#"myCircle diameter: %lf", myCircle.diameter);
NSLog(#"myCircle circumference: %lf", myCircle.circumference);
}
return 0;
}
There are of course many ways to set this up. I can remember being confused when starting out, below is an alternative example to give you something else to look at.
It is not intended to be fancy but just bare-bones so that you can see a minimal setup of the class with an initializer.
Note that the only value initialized is the const pi, of course, the radius can be initialized there as well, as nhgrif's example shows quite nicely.
Hope this helps!
// Circle.h
#import <Foundation/Foundation.h>
#interface Circle : NSObject
{
double radius;
double pi;
}
#property double radius, pi;
-(double) getArea;
-(double) getDiameter;
-(double) getCircumference;
#end
And then the implementation:
// Circle.m
#import "Circle.h"
#implementation Circle
#synthesize radius, pi;
// Initialize with const pi:
- (id)init {
self = [super init];
if (self) {
pi = 3.14159;
NSLog(#"Circle created.");
}
return self;
}
-(double) getArea {
return pi*radius*radius;
}
-(double) getDiameter {
return 2*radius;
}
-(double) getCircumference {
return 2*pi*radius;
}
#end
And then for main:
// main.m
#import <Foundation/Foundation.h>
#import "Circle.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
Circle *aCircle = [[Circle alloc] init];
// Use an arbitrary value:
[aCircle setRadius:2];
NSLog(#"Area = %f",[aCircle getArea]);
NSLog(#"Circumference = %f",[aCircle getCircumference]);
NSLog(#"Diameter = %f",[aCircle getDiameter]);
NSLog(#"Check pi = %f",[aCircle pi]);
}
return 0;
}

How do you properly compose the #interface section? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am fairly new to Objective-C and created this basic program. It is giving me errors on the #interface section, is there any simple explanation that you could give a beginner on how to build both the #interface and #implementation sections? What is wrong with the program below?
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject {
//declare methods
- (void) setWidth: (int) a;
- (void) setHieght: (int) b;
- (double) perimeter;
- (double) area;
}
#end
#implementation Rectangle
{
double area;
double perimeter;
int width;
int height;
}
- (void) setWidth: (int) a
{
width = a;
}
- (void) setHieght: (int) b
{
hieght = b;
}
#end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * Rectangle = [[NSAutoreleasePool alloc] init];
int a = 4
int b = 5
int area = a * b;
int perimeter = 2 * (a +b);
NSLog(#"With width of %i and Hieght of %i", a, b);
NSLog(#"The perimeter is %i", perimeter);
NSLog(#"The Area is %i", area);
[pool drain];
return 0;
}
Your listing your methods where ivars are supposed to go. It should be:
#interface Rectangle : NSObject {
//instance variables here
}
// declare methods or properties here
- (void) setWidth: (int) a;
- (void) setHieght: (int) b;
- (double) perimeter;
- (double) area;
#end
You can, as has been pointed out, just simply delete the curly braces.
There are several problems in your code, we'll see them later, but as beginner you need to know few things:
main() is for main.m class in your project, don't mess-up with that here and there, use init() instead
you don't declare methods inside {} scope of your #implementaion
After #end of #implementation nothing that is to be execute should be written
#implementation shouldn't be bounded in {} scope as it end with #end
And some more, find it here http://www.slideshare.net/musial-bright/objective-c-for-beginners
So your should look like this:
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
//declare methods
- (void) setWidth: (int) a;
- (void) setHieght: (int) b;
- (double) perimeter;
- (double) area;
#end
#implementation Rectangle
    {
double area;
double perimeter;
int width;
int height;
    }
- (void) setWidth: (int) a {
width = a;
}
- (void) setHieght: (int) b {
height = b;
}
- (id)init
{
self = [super init];
if (self) {
// Custom initialization
int a = 4;
int b = 5;
int area = a * b;
int perimeter = 2 * (a +b);
NSLog(#"With width of %i and Hieght of %i", a, b);
NSLog(#"The perimeter is %i", perimeter);
NSLog(#"The Area is %i", area);
}
return self;
}
#end

polymorphism methods in ios

I have a doubt in implementing oops concept in objective-c.Is Pholyorphism possible in objective-c. How to implement polymorphism in objective-c.please explain with example?
Every method, including class methods, is dynamic in Objective-C.
One very basic approach would be:
Declare the base interface:
#interface MONConstantColor : NSObject
- (UIColor *)color;
#end
Define the base implementation:
#implementation MONConstantColor
- (UIColor *)color { return /* ...do/ret something appropriate */; }
#end
Then create some variations:
#interface MONRedColor : MONConstantColor
#end
#implementation MONRedColor
- (UIColor *)color { return [UIColor redColor]; }
#end
#interface MONYellowColor : MONConstantColor
#end
#implementation MONYellowColor
- (UIColor *)color { return [UIColor yellowColor]; }
#end
- (HomeWorkResult *)homeWorkResultFromHomeWorkTask:(HomeWorkTask *)task
{
if (!self.lazy) {
return [self HW_performHomeWorkTask:task];
}
StackOverflowPost *post = [StackOverflow postHomeWorkTask:task];
for (id user in post.responders) {
// Here is the pholyorphism[sic].
// First, test to see if a stack overflow user is able to do home work tasks.
if ([user respondsToSelector:#selector(homeWorkResultFromHomeWorkTask:)]) {
// Next, have the user do the home work task.
HomeWorkResult *result = [user homeWorkResultFromHomeWorkTask:task];
// If there is a result, return that result.
if (result) {
return result;
}
}
}
// Finally, if no stack overflow user does home work tasks or if there was no
// result perform the task yourself.
return [self HW_performHomeWorkTask:task];
}
The word polymorphism means having many forms
Objective-C polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Consider the example, we have a class Shape that provides the basic interface for all the shapes. Square and Rectangle are derived from the base class Shape.
We have the method printArea that is going to show about the OOP feature polymorphism.
#import <Foundation/Foundation.h>
#interface Shape : NSObject
{
CGFloat area;
}
- (void)printArea;
- (void)calculateArea;
#end
#implementation Shape
- (void)printArea{
NSLog(#"The area is %f", area);
}
- (void)calculateArea{
}
#end
#interface Square : Shape
{
CGFloat length;
}
- (id)initWithSide:(CGFloat)side;
- (void)calculateArea;
#end
#implementation Square
- (id)initWithSide:(CGFloat)side{
length = side;
return self;
}
- (void)calculateArea{
area = length * length;
}
- (void)printArea{
NSLog(#"The area of square is %f", area);
}
#end
#interface Rectangle : Shape
{
CGFloat length;
CGFloat breadth;
}
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
#end
#implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
length = rLength;
breadth = rBreadth;
return self;
}
- (void)calculateArea{
area = length * breadth;
}
#end
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Shape *square = [[Square alloc]initWithSide:10.0];
[square calculateArea];
[square printArea];
Shape *rect = [[Rectangle alloc]
initWithLength:10.0 andBreadth:5.0];
[rect calculateArea];
[rect printArea];
[pool drain];
return 0;
}
use this link as refernce
http://www.tutorialspoint.com/objective_c/objective_c_polymorphism.htm

Objective-C getter/ setter

I'm trying to work my way through an Objective-C tutorial. In the book there is this example:
#interface
{
int width;
int height;
XYPoint *origin;
}
#property int width, height;
I thought, "hey there's no getter/setter for the XYPoint object. The code does work though." Now i'm going maybe to answer my own question :).
I thinks its because "origin" is a pointer already, and whats happening under the hood with "width" and "height", is that there is going te be created a pointer to them..
Am i right, or am i talking BS :) ??
I just dont get it. here's main:
#import "Rectangle.h"
#import "XYPoint.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle *myRect = [[Rectangle alloc] init];
XYPoint *myPoint = [[XYPoint alloc] init];
[myPoint setX: 100 andY: 200];
[myRect setWidth: 5 andHeight: 8];
myRect.origin = myPoint;
NSLog (#"Rectangle w = %i, h = %i",
myRect.width, myRect.height);
NSLog (#"Origin at (%i, %i)",
myRect.origin.x, myRect.origin.y);
NSLog (#"Area = %i, Perimeter = %i",
[myRect area], [myRect perimeter]);
[myRect release];
[myPoint release];
[pool drain];
return 0;
}
And here's the Rectangle object:
#import "Rectangle.h"
#import "XYPoint.h"
#implementation Rectangle
#synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
- (void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
-(int) area
{
return width * height;
}
-(int) perimeter
{
return (width + height) * 2;
}
-(XYPoint *) origin
{
return origin;
}
#end
What i dont understand is this line in main: myRect.origin = myPoint; I did not make a setter for it..
BTW thanks for your fast reply's
What i dont understand is this line in main: myRect.origin = myPoint; I did not make a setter for it..
There is both a getter and a setter (collectively referred to as accessors) created for origin in the Rectangle class. If you have a look in the implementation for Rectangle, this is the getter:
-(XYPoint *) origin
{
return origin;
}
and this is the setter:
- (void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
And as of Objective-C 2.0 calling:
myRect.origin = myPoint;
is equivalent to:
[myRect setOrigin:myPoint];
Declaring getters and setters using #property (and then implementing them using #synthesize) is only one way of declaring and creating accessors, and is there for a convenience if you have lots of properties to declare in the class interface. As Schildmeijer said, #property int width is equivalent to declaring two methods:
- (int)width;
- (void)setWidth:(int)newWidth;
Due to the dynamically-bound nature of Objective-C method calls, you don't even have to declare the getter and setter methods in the interface, although it is generally best practice to do so if you are advertising them as publicly available to other classes.
You can think of a property declaration as being equivalent to declaring two accessor methods. Thus
#property int width;
is equivalent to:
- (int)width;
- (void)setWidth:(int)newWidth;
//Rectangle.h
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
#property int Width;
#property int Height;
-(int)Area;
#end
//Rectangle.m
#import "Rectangle.h"
#implementation Rectangle
#synthesize Width;/*Will create value Width , Setter called"setWidth" and Getter called "Width"*/
#synthesize Height;/*Will create value Height , Setter called"setHeight" and Getter called "Height"*/
-(int)Area
{
return Width*Height;
}
#end
// main.m
#import <Cocoa/Cocoa.h>
#import "Rectangle.h"
int main(int argc, const char * argv[])
{
Rectangle *myRectangle = [Rectangle new];
myRectangle.Width=3;
myRectangle.Height=5;
printf("Area = %d\n",[myRectangle Area]);
//Or
[myRectangle setWidth:5];
[myRectangle setHeight:6];
printf("Area = %d\n",[myRectangle Area]);
}
If you want to make Getter only or rename getter and setter
• readonly
• getter = newGetterName
• setter = new SetterName
example
//Rectangle.h
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
#property (getter = getWidth) int Width;
#property (readonly) int Height;
#end
You don't say what code is working, or what your expectations are for "working".
The above interface will create simple accessor methods for width and height that can be called from other objects as [object setWidth:1]; or object.width = 1; - these two are analogous.
Origin is some other object type and is a pointer, yes. But you would still want to declare a property for it to generate accessor methods.
Getters and setters are mostly useful if you need to access an instance variable from another class or you're using bindings to get/set them. So my guess would be that you need this functionality for the width and height but not for the origin. Note that the getters/setters do not make pointers out of the integers as you stated might be the reason. Ints are ints and getters/setters do not change that.