H 和.m 文件中@接口定义之间的差异

通常我们会用

@interface interface_name : parent_class <delegates>
{
......
}
@end

方法在.h 文件和.m 文件中,我们综合了在.h 文件中声明的变量的属性。

但是在某些代码中,这个@interface... ...@end 方法保存在。M 文件也。这是什么意思?他们之间有什么区别?

还给出一些关于在.m 文件中定义的接口文件的 getter 和 setter 的单词..。

提前感谢

31179 次浏览

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

you can even create other classes in .m file, for instance other small classes which inherit from the class declared in .h file but having some slight different behaviour. You could use this in a factory pattern

The concept is that you can make your project much cleaner if you limit the .h to the public interfaces of your class, and then put private implementation details in this class extension.

when you declare variable methods or properties in ABC.h file , It means these variables properties and methods can be access outside the class

@interface Jain:NSObject
{
NSString *_name;
}


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

@Interface allows you to declare private ivars, properties and methods. So anything you declare here cannot be accessed from outside this class. In general, you want to declare all ivars, properties and methods by default as private

Simply say when you declare variable methods or properties in ABC.m file , It means these variables properties and methods can not be access outside the class

@interface Jain()
{
NSString *_name;
}


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