snapfish
snapfish

Reputation: 175

order of methods in objective C

Does it matter how I order my methods in objective-C (mainly in the implementation file)?

@implementation UDDPlayerDetailsViewController

- (IBAction)cancel:(id)sender
{
    [self.delegate playerDetailsViewControllerDidCancel:self];
}

-(IBAction)done:(id)sender
{
    [self.delegate playerDetailsViewControllerDidSave:self];
}

so in a situation like this, it obviously does not matter which one(either cancel or done) i place first but im wondering if this holds true for all methods? Does the compiler just read through everything and then takes action or are there circumstances where placing one ahead of another in the file will have different results?

Upvotes: 1

Views: 605

Answers (3)

Duncan C
Duncan C

Reputation: 131408

It used to matter, but it doesn't any more. That is because of the compiler, not the language.

It used to be that you had to declare a method before using it. Thus, if you had

-(void) methodA;
{
  [self methodB];
}

-(void) methodB;
{
  //Do stuff
}

You would get a warning that methodB was not defined.

If methodB was declared in your @interface you were fine.

Newer versions of the Clang compiler are able to handle forward references. I don't remember exactly which version of Xcode included this change. Xcode 4.6, maybe?

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

The order of methods does not matter, both in the @implementation and in the @interface sections.

  • In the @interface section it does not matter because there is no dependencies between methods there,
  • In the @implementation section it does not matter, because the @interface section (perhaps in combination with the class extension @interface) has listed all methods for the compiler, providing their signatures and removing potential ambiguities
  • Finally, the compiler lets you define completely "private" methods in the implementation section itself. The compiler is smart enough to look ahead for these added methods.

Upvotes: 3

Ben Pious
Ben Pious

Reputation: 4805

I know of no situation where it matters in Objective-C. In regular C, you need to declare methods before using them, so

void usesUndeclared() {

    undeclaredFunction();
}

void undeclaredFunction() {}

will be an error, but

void undeclaredFunction;
void usesUndeclared() {

    undeclaredFunction();
}

void undeclaredFunction() {}

Upvotes: 0

Related Questions