Difference between @interface definition in .h and .m file

It’s common to put an additional @interface that defines a category containing private methods:

Person.h:

@interface Person
{
    NSString *_name;
}

@property(readwrite, copy) NSString *name;
-(NSString*)makeSmallTalkWith:(Person*)person;
@end

Person.m:

@interface Person () //Not specifying a name for the category makes compiler checks that these methods are implemented.

-(void)startThinkOfWhatToHaveForDinner;
@end


@implementation Person

@synthesize name = _name;

-(NSString*)makeSmallTalkWith:(Person*)person
{
    [self startThinkOfWhatToHaveForDinner];
    return @"How's your day?";
}


-(void)startThinkOfWhatToHaveForDinner
{

}

@end

The ‘private category’ (the proper name for a nameless category is not ‘private category’, it’s ‘class extension’) .m prevents the compiler from warning that the methods are defined. However, because the @interface in the .m file is a category you can’t define ivars in it.

Update 6th Aug ’12: Objective-C has evolved since this answer was written:

  • ivars can be declared in a class extension (and always could be – the answer was incorrect)
  • @synthesize is not required
  • ivars can now be declared in braces at the top of @implementation:

that is,

@implementation { 
     id _ivarInImplmentation;
}
//methods
@end

Leave a Comment