Obj-C“@interface”的类文件?

时间:2012-09-04 09:40:29

标签: iphone objective-c ios ios5

  

可能重复:
  Difference between @interface definition in .h and .m file

Obj C类文件有两个文件.h和.m,其中.h包含接口定义(@interface),。m保存其实现(@implementation)

但我在某些课程中看到.h和.m都出现了@interface?

两个文件中@interface的需求是什么?有没有具体的理由这样做?如果这样做有什么好处?

4 个答案:

答案 0 :(得分:2)

.m 文件中的@interface宏通常用于私有iVars和属性,用于有限的可见性。当然这完全是可选的,但无疑是一种很好的做法。

答案 1 :(得分:2)

.h文件中的@interface通常是公共接口,这是您将声明继承的那个,例如

   @interface theMainInterface : NSObject

注意冒号:,然后是@interfaceNSObject继承的超级对象,我相信这只能在.h文件中完成。您也可以使用类别声明@interface,例如

   @interface theMainInterface(MyNewCatergory)

这意味着您可以在一个.h文件中拥有多个@interface,例如

   @interface theMainInterface : NSObject

        // What ever you want to declare can go in here. 

   @end

   @interface theMainInterface(MyNewCategory)

        // Lets declare some more in here.

   @end

在.h文件中声明这些类型的@interface通常会将在其中声明的所有内容公开。

但您可以在.m文件中声明私有@interface,该文件将执行以下三项内容之一:私下扩展所选@interface或向选定的@interface添加新类别或声明一个新的私人@interface

您可以通过向.m文件中添加类似内容来实现此目的。

  @interface theMainInterface()
      // This is used to extend theMainInterface that we set in the .h file.
      // This will use the same @implemenation
  @end

  @implemenation theMainInterface()
      // The main implementation.
  @end

  @interface theMainInterface(SomeOtherNewCategory)
      // This adds a new category to theMainInterface we will need another @implementation for this.
  @end 

  @implementation theMainInterface(SomeOtherNewCategory)
      // This is a private category added the .m file
  @end

  @interface theSecondInterface()
      // This is a whole new @interface that we have created, this is private
  @end

  @implementation theSecondInterface()
     // The private implementation to theSecondInterface
  @end

这些都以相同的方式工作,唯一的区别是有些是private,有些是public,有些是categories

我不确定您是否可以继承.m文件中的@interface

希望这有帮助。

答案 2 :(得分:1)

如果我们想声明一些私有方法,那么我们在.m文件中使用@interface声明。

答案 3 :(得分:1)

.m文件中出现的@interface通常用于内部类别定义。将有一个类别名称,后跟@interface语句,格式如下

@interface ClassName (CategoryName)

@end

当类别名称为以下格式为空时,其中的属性和方法将被视为私有。

@interface ClassName ()

@end

另请注意,您可能在私有类别中声明为readwrite,在标头中只读取readonly。如果两个声明都是readwrite,编译器会抱怨。

// .h file
@interface ClassName
@property (nonatomic, strong, readonly) id aProperty;
@end

// .m file
@interface ClassName()
@property (nonatomic, strong) id aProperty;
@end