PDA

View Full Version : Simple Addition in Obj-C




Aegaeon
May 26, 2009, 12:39 AM
Hi everyone, I'm just getting my feet wet with Obj-C here. I'm going through Stephen Kochan's Programming in Objective-C 2.0, and have gotten stuck on this small problem.

Basically, I'm trying to add two numbers. I could easily do this the C way, by declaring 2 variables (either predefined or using scanf to get user input) but in doing it the Obj-C way, I am here:


#import <Foundation/Foundation.h>

//interface section
@interface Addition : NSObject
{
int numOne;
int numTwo;

}

- (void) setNumOne: (int) a;
- (void) setNumTwo: (int) b;
- (void) print;
- (int) total;

@end



//implementation section
@implementation Addition

- (void) setNumOne: (int) a
{
numOne = a;
}

- (void) setNumTwo: (int) b
{
numTwo = b;
}


- (int) total
{
return (numOne + numTwo);
}


- (void) print
{
NSLog(@"%i + %i = %i", numOne, numTwo, total);
}


@end

//program section
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Addition *myAddition = [[Addition alloc] init];

[myAddition setNumOne: 5];
[myAddition setNumTwo: 7];
[myAddition print];

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


However, I'm having two issues. One, im getting "error, 'total' undeclared (first use in this function)" in my "- (void) print; " method implementation, and secondly, the total readout says "5+7=0". What am I doing wrong here? Thanks in advance! :)



Krevnik
May 26, 2009, 12:50 AM
You define 'total' as a method that needs to be called like '[self total]', and then reference it like a variable 'total'.

It is looking for the variable 'total', which doesn't exist.

Aegaeon
May 26, 2009, 01:26 AM
You define 'total' as a method that needs to be called like '[self total]', and then reference it like a variable 'total'.

It is looking for the variable 'total', which doesn't exist.

Thanks for the quick reply. How would I define 'total' in that form? And If I do that, then I would be able to reference it within the NSLog statement? I also tried directly calling the method in an instance, with:

[myAddition total];

which shows as:

5 + 7 = -1803819306


The book uses a fraction example (with just placing %/% = numerator/denominator appropriately in the NSLog statement), however thus far none of the examples use calculations within the method implementation.

Thanks again. :)

mactweak
May 26, 2009, 03:36 AM
Hi Aegaeon,

I tried your code at home, but changed the print method:

- (void) print
{
NSLog(@"%i + %i = %i", numOne, numTwo, [self total]);
}


And it perfectly works...
Output:
5 + 7 = 12

Thomas Harte
May 26, 2009, 04:46 AM
One of the differences between C++ and Objective-C is that method calls can't be made without explicitly naming their target. Whereas in C++ you can call other object methods as though they were ordinary C functions with an implicit "this->" because of the namespace rules, in Objective C you must always do [self method].

That said, I would highly recommend that you read up on Objective-C's automatic getters and setters (which seem to be a relatively recent language addition; they're not mentioned in any of the books I have from circa 2002).

If you have a getter and setter, such as:


- (int)num;
- (void)setNum:(int)n;


Then you can subsequently use class.num = 3 to implicitly call the setter and int c = class.num to implicitly call the getter. Note that, as per the normal conventions, class is a pointer to the relevant class so the dot operator is used here in a quite distinct way to the way it is used in C or C++.

You can also do the following:

@interface whatever: NSObject{
NSString *string;
}

@property (nonatomic, retain) NSString *string;

...

@implementation whatever

@synthesize string;
...

@end
Which will cause the compiler to automatically generate a valid setter and getter for the member variable 'string'. The various parameters to @property determine whether you want just a setter, just a getter or both, whether you're expecting an object that needs to be retained, etc.

Sander
May 26, 2009, 05:19 AM
I realize you are just doing some exercises but you might as well get used to thinking about these things: Is an "addition" really an "object"?

lee1210
May 26, 2009, 08:40 AM
I realize you are just doing some exercises but you might as well get used to thinking about these things: Is an "addition" really an "object"?

As long as your object system is a model for construction, of course!

-Lee

Aegaeon
May 26, 2009, 11:20 AM
Hi Aegaeon,

I tried your code at home, but changed the print method:

- (void) print
{
NSLog(@"%i + %i = %i", numOne, numTwo, [self total]);
}


And it perfectly works...
Output:
5 + 7 = 12

Ahh, thats where I went wrong then. Thank you, I've tried the code on mine and it works fine. :)

One of the differences between C++ and Objective-C is that method calls can't be made without explicitly naming their target. Whereas in C++ you can call other object methods as though they were ordinary C functions with an implicit "this->" because of the namespace rules, in Objective C you must always do [self method].

That said, I would highly recommend that you read up on Objective-C's automatic getters and setters (which seem to be a relatively recent language addition; they're not mentioned in any of the books I have from circa 2002).

If you have a getter and setter, such as:


- (int)num;
- (void)setNum:(int)n;


Then you can subsequently use class.num = 3 to implicitly call the setter and int c = class.num to implicitly call the getter. Note that, as per the normal conventions, class is a pointer to the relevant class so the dot operator is used here in a quite distinct way to the way it is used in C or C++.

You can also do the following:

@interface whatever: NSObject{
NSString *string;
}

@property (nonatomic, retain) NSString *string;

...

@implementation whatever

@synthesize string;
...

@end
Which will cause the compiler to automatically generate a valid setter and getter for the member variable 'string'. The various parameters to @property determine whether you want just a setter, just a getter or both, whether you're expecting an object that needs to be retained, etc.

Thanks for the info, I have actually redone my example using the synthesizer accessor methods, and have run into a small problem. I can see how this makes life easier in terms of not having to manually manage certain simple method declarations.


#import <Foundation/Foundation.h>

//interface section
@interface Addition : NSObject
{
int numOne;
int numTwo;
}

@property int numOne, numTwo;

- (void) print;
- (int) total;

@end



//implementation section
@implementation Addition
@synthesize numOne, numTwo;

- (int) total
{
return ((int)numOne + (int)numTwo);
}

- (void) print
{
NSLog(@"%i + %i = %i", numOne, numTwo, [self total]);
}


@end

//program section
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Addition *myAddition = [[Addition alloc] init];

Addition.numOne = 5;
Addition.numTwo = 8;

[myAddition print];
[myAddition total];

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




This is the one error I have however, a syntax error before the '.'
http://kttns.org/u3zwj

Thanks again for the help! :)

I realize you are just doing some exercises but you might as well get used to thinking about these things: Is an "addition" really an "object"?

Haha, well the main reason why I'm doing this to start out small, and use this as a foundation to build up on more complex syntax later on as I learn more. I realize right now the same result can be achieved in a fraction of the code, but I'm trying to get into the object-oriented way of doing things. Perhaps I can make a calculator of some sort towards the end.

lee1210
May 26, 2009, 11:29 AM
Haha, well the main reason why I'm doing this to start out small, and use this as a foundation to build up on more complex syntax later on as I learn more. I realize right now the same result can be achieved in a fraction of the code, but I'm trying to get into the object-oriented way of doing things. Perhaps I can make a calculator of some sort towards the end.

I think Sander's point is that normally an Object is used to model the concept of... an... object. So normally it will be a noun. Patient, Animal, etc. Addition is normally the act of adding, which doesn't make as much sense (except its other use, in construction, as I joked above). If all the class did was add, you might call it "Adder" instead of "Addition".

-Lee

Aegaeon
May 26, 2009, 02:15 PM
I think Sander's point is that normally an Object is used to model the concept of... an... object. So normally it will be a noun. Patient, Animal, etc. Addition is normally the act of adding, which doesn't make as much sense (except its other use, in construction, as I joked above). If all the class did was add, you might call it "Adder" instead of "Addition".

-Lee

True :)

Oh, and I found out my mistake from the last post. When I was accessing the properties, I tried to ask the class rather than the instance, so fixing it from


Addition.numOne = 5;


to


myAddition.numOne = 5;


did the job. Careless mistake.

Sander
May 27, 2009, 04:16 AM
I think Sander's point is that normally an Object is used to model the concept of... an... object. So normally it will be a noun. Patient, Animal, etc. Addition is normally the act of adding, which doesn't make as much sense (except its other use, in construction, as I joked above). If all the class did was add, you might call it "Adder" instead of "Addition".

-Lee

Right, that was my point. Thanks for the explanation though Lee; being a non-native speaker I didn't know the "construction" term (and still don't understand it) so I was scratching my head for a while thinking perhaps there was some computer science concept which had evaded me up till now...

lee1210
May 27, 2009, 07:07 AM
Right, that was my point. Thanks for the explanation though Lee; being a non-native speaker I didn't know the "construction" term (and still don't understand it) so I was scratching my head for a while thinking perhaps there was some computer science concept which had evaded me up till now...

Well, I never would have known from your posts.
An addition, to a home for example, would be a room or rooms added after initial construction. For the vast majority of people this would be very rarely used.

-Lee

Thomas Harte
May 27, 2009, 07:34 AM
Well, I never would have known from your posts.
An addition, to a home for example, would be a room or rooms added after initial construction. For the vast majority of people this would be very rarely used.
I also think that might be American English only. I guess the British English would be an extension. Though without access to the OED, I'm not certain.