I'm learning Objective-C and just trying out some sample code. I am getting the following error message:
unrecognized selector sent to class
Here is my code.
Basics.m
#import <Foundation/Foundation.h>
#import "Fraction.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Fraction *myFraction;
// Create an instance of a Fraction
myFraction = [Fraction alloc];
myFraction = [Fraction init];
// set Fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];
// Display the value using the print method
NSLog(@"The value of myFraction is:");
[myFraction print];
[myFraction release];
[pool drain];
return 0;
}
Fraction.h
#import <Foundation/Foundation.h>
// -- interface section --//
@interface Fraction : NSObject {
int numerator;
int denominator;
}
// public method signatures
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
@end
Fraction.m
//--implementation section --//
@implementation Fraction
-(void) print
{
NSLog(@"%i/%i",numerator,denominator);
}
-(void) setNumerator: (int) n
{
numerator = n;
}
-(void) setDenominator: (int) d
{
denominator = d;
}
@end
alloc
is a class method, but init
is an instance method. In your code, the compiler is complaining that it can't find any class method named init
, which is accurate. To correct this, you should call init
upon the instance you received back from alloc
, like so:
myFraction = [Fraction alloc];
myFraction = [myFraction init];
but the most common pattern is to nest the calls like this:
// calls -init on the object returned by +alloc
myFraction = [[Fraction alloc] init];
This also helps you avoid errors that might occur by calling methods on an object that has been allocated, but not yet initialized.
In addition to what has been said regarding the nested alloc
/ init
call, something you may be interested in is description
. In your Fraction
class implementation, add a method like this:
- (NSString *) description
{
return [NSString stringWithFormat:@"%i/%i", numerator, denominator];
}
Now, you can use it directly in NSLog
statements like this:
// set Fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];
// Display the value using the print method
NSLog(@"The value of myFraction is: %@", myFraction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With