redconservatory
redconservatory

Reputation: 21924

Unrecognized selector sent to class

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

Upvotes: 5

Views: 27086

Answers (3)

Bryan Bryce
Bryan Bryce

Reputation: 1379

I know this answer was awhile ago so I wanted to give a little update. If you are using alloc/init to initialize you can shorten it to just

[Fraction new]

and that will be equivalent.

Upvotes: 2

dreamlax
dreamlax

Reputation: 95335

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);

Upvotes: 4

Justin Spahr-Summers
Justin Spahr-Summers

Reputation: 16973

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.

Upvotes: 15

Related Questions