.h 和 .m 文件中 @interface 定义的区别 [英] Difference between @interface definition in .h and .m file

查看:29
本文介绍了.h 和 .m 文件中 @interface 定义的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我们使用

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

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

method in .h file and in .m file we synthesis the properties of variables declared in .h file.

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

But in some code, this @interface.....@end method is kept in the .m file also. What does it mean? What is the difference between them?

另外给出一些关于.m文件中定义的接口文件的getter和setter的词...

Also give some words about getters and setters for the interface file that is defined in .m file...

提前致谢

推荐答案

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

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

私有类别"(无名类别的正确名称不是私有类别",而是类扩展").m 可防止编译器警告已定义方法.但是,由于 .m 文件中的 @interface 是一个类别,因此您无法在其中定义 ivars.

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.

2012 年 8 月 6 日更新:自从撰写此答案以来,Objective-C 已经发展:

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

  • ivars 可以在类扩展中声明(并且总是可以 - 答案不正确)
  • @synthesize 不是必需的
  • ivars 现在可以在 @implementation 顶部的大括号中声明:
  • 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:

也就是

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

这篇关于.h 和 .m 文件中 @interface 定义的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆