我们通常使用
@interface interface_name : parent_class <delegates>
{
......
}
@end
.h 文件和.m 文件中的方法我们综合了.h 文件中声明的变量的属性。
但在某些代码中,这个@interface.....@end 方法也保存在.m 文件中。这是什么意思?它们有什么区别?
同时给出一些关于 .m 文件中定义的接口(interface)文件的 getter 和 setter...
提前致谢
最佳答案
添加一个额外的 @interface
来定义一个包含私有(private)方法的类别是很常见的:
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
“私有(private)类别”(无名类别的正确名称不是“私有(private)类别”,而是“类扩展”).m 防止编译器警告方法已定义。但是,由于 .m 文件中的 @interface
是一个类别,因此您不能在其中定义 ivars。
2012 年 8 月 6 日更新:自编写此答案以来,Objective-C 已经发展:
ivars
可以在类扩展中声明(并且总是可以 - 答案不正确)@synthesize
不是必需的ivars
现在可以在@implementation
顶部的大括号中声明:
也就是说,
@implementation {
id _ivarInImplmentation;
}
//methods
@end
关于objective-c - .h 和 .m 文件中的@interface 定义之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3967187/