关于C:.h和.m文件中@interface定义的区别

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

我们通常使用

1
2
3
4
5
@interface interface_name : parent_class <delegates>
{
......
}
@end

方法在.h文件和.m文件中合成.h文件中声明的变量的属性。

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

还提供一些关于在.m文件中定义的接口文件的getter和setter的单词…

提前谢谢


通常会添加一个额外的@interface来定义包含私有方法的类别:

人:H:

1
2
3
4
5
6
7
8
@interface Person
{
    NSString *_name;
}

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

人:M:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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

"private category"(无名称类别的正确名称不是"private category",而是"class extension")。m防止编译器警告定义了方法。但是,由于.m文件中的@interface是一个类别,因此不能在其中定义ivar。

更新日期:2012年8月6日:自本答案撰写以来,客观-C已经发展:

  • 可以在类扩展中声明ivars(并且始终可以是-答案不正确)
  • 不需要@synthesize
  • 现在可以在@implementation顶部的大括号中声明ivars

也就是说,

1
2
3
4
5
@implementation {
     id _ivarInImplmentation;
}
//methods
@end


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

1
2
3
4
5
6
7
8
@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

1
2
3
4
5
6
7
8
@interface Jain()
    {
        NSString *_name;
    }

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


甚至可以在.m文件中创建其他类,例如,其他继承自.h文件中声明的类,但行为略有不同的小类。你可以在工厂模式中使用这个