Unrecognized selector sent to class

I am learning Objective-C and just trying sample code. I get 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 
+4
source share
3 answers

alloc is a class method, but init is an instance method. In your code, the compiler complains that it cannot find any class method called init , which is exact. To fix this, you must call init on the instance you received from alloc , for example:

 myFraction = [Fraction alloc]; myFraction = [myFraction init]; 

but the most common pattern is to nest calls like this:

 // calls -init on the object returned by +alloc myFraction = [[Fraction alloc] init]; 

It also helps to avoid errors that may occur when calling methods on an object that has been allocated but not yet initialized.

+15
source

In addition to what was said about the alloc / init nested call, you might be interested in description . In the implementation of the Fraction class, add a method similar to this:

  - (NSString *) description { return [NSString stringWithFormat:@"%i/%i", numerator, denominator]; } 

Now you can use it directly in NSLog statements, for example:

 // 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); 
+4
source

I know this answer was a while ago, so I wanted to give a small update. If you use alloc / init to initialize, you can shorten it to

[Fraction new]

and it will be equivalent.

+2
source

Source: https://habr.com/ru/post/1334873/


All Articles