Properly Declaring Methods in Classes

If you’re beginning to learn Objective-C like I am, things like this aren’t immediately obvious. I was trying to fool around with creating my own class, and I kept getting this warning
warning: no '-blah blah blah' method found along with an accompanying
warning: 'ClassName' may not respond to '-blah blah blah'

The really annoying part was that, despite these warnings, the code still worked just fine. Turns out, my issue was that I had this method in my class implementation (PolygonShape.m):

[code lang=”objc”]
– (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max{
if (self = [super init]) {
//initialize defaults so that it doesnt choke if being told to init with something out of range
numberOfSides = 5;
minimumNumberOfSides = 3;
maximumNumberOfSides = 12;

//now init with user values.
[self setMinimumNumberOfSides:min];
[self setMaximumNumberOfSides:max];
//Must set numberOfSides AFTER these two, so that the setNumberOfSides method can reference them
[self setNumberOfSides:sides];
return self;

Basically, it was an alternate init method for my class ‘PolygonShape’. The problem is that, while the ‘-init’ method is declared in foundation.h as a method for all NSObjects (from which my PolygonShape class inherits), the ‘-initWithNumberOfSides:andsoon’ method was not. As a result, the compiler couldn’t be sure if this method actually existed in the implementation file (PolygonShape.m). To clear this up, and do things properly, the method has to be declared in the header file for the class (PolygonShape.h in my case) as such:

[code lang=”objc”]
– (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max;

That took care of all my issues, and hopefully if you found this page via Google, yours too.
[ad name=”mid-post”]

Leave a Reply

Your email address will not be published. Required fields are marked *