Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized selector sent to class

Tags:

objective-c

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
like image 533
redconservatory Avatar asked Jan 10 '11 01:01

redconservatory


2 Answers

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.

like image 110
Justin Spahr-Summers Avatar answered Nov 15 '22 06:11

Justin Spahr-Summers


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);
like image 27
dreamlax Avatar answered Nov 15 '22 05:11

dreamlax