iOS App开发 OC 第一天, @interface设计思维

从Swift 到 OC 第一天, @interface设计思维

tags: OC 30 day

第一次打开 objc 的文件,看到了一个关键字 @interface

究竟什么是interface ?

先看看wiki怎么说吧:
interface :
定义部分,清楚定义了类的名称、成员变数和方法。 以关键字@interface作为开始,@end作为结束。

[color=#d2ed28] In object-oriented programming, a protocol or interface is a common means for unrelated objects to communicate with each other. These are definitions of methods and values which the objects agree upon in order to cooperate.
接口约定了对象间交互的属性和方法,使得对象间无需了解对方就可以协作。

interface 是否就是我们在C++ 裏看到的 class ?

Objective-C中强制要求将类的定义(interface)与实现(implementation)分为两个部分。
类的定义档案遵循C语言之惯例以.h为字尾,实现档案以.m为字尾。
这也就是为什么我们在Objc里看到.h .m 的文件。

对比@interface和@implementation
@interface 我们干过的事:
1、继承
2、声明协议
3、定义实例变量(@interface后面加大括号那种)
4、定义@property
5、声明方法
@implementation 我们干过的和可以干的事:
1、继承
2、定义实例变量
3、合成属性(@synthesize和@dynamic)
4、实现方法(包括协议方法)

interface 与 implementation 的简要关係

interface

定义部分,清楚定义了类的名称、成员变数和方法。 以关键字@interface作为开始,@end作为结束。

@interface MyObject : NSObject {    int memberVar1; // 实体变量    id  memberVar2;}+(return_type) class_method; // 类方法-(return_type) instance_method1; // 实例方法-(return_type) instance_method2: (int) p1;-(return_type) instance_method3: (int) p1 andPar: (int) p2;@end

方法前面的 +/- 号代表函式的类型:加号(+)代表类别方法(class method),不需要实例就可以呼叫,与C++ 的静态函式(static member function)相似。减号(-)即是一般的实例方法(instance method)。

implementation

实现区段则包含了公开方法的实现,以及定义私有(private)变数及方法。 以关键字@implementation作为区段起头,@end结尾。

@implementation MyObject {  int memberVar3; //私有实体变数}+(return_type) class_method {    .... //method implementation}-(return_type) instance_method1 {     ....}-(return_type) instance_method2: (int) p1 {    ....}-(return_type) instance_method3: (int) p1 andPar: (int) p2 {    ....}@end

值得一提的是不只Interface区段可定义实体变数,Implementation区段也可以定义实体变数,两者的差别在于存取权限的不同,Interface区段内的实体变数默认权限为protected,宣告于implementation区段的实体变数则默认为private,故在Implementation区段定义私有成员更符合物件导向之封装原则,因为如此类别之私有资讯就不需曝露于公开interface(.h档案)中。

interface 就是为了给调用者看的

是和调用者的一个protocol,没错,就是protocol。

interface 的正确姿势

看过不少代码,从@interface设计上多少就能看出作者的水平,分享下我对于这个问题的一些拙见。

只暴露外部需要看到的

// Sark.h @interface SarkViewController : NSObject <NSXMLParserDelegate /*1*/, NSCopying> {     NSString *_name; // 2     IBOutlet UITextField *_nameTextField; // 2 } @property (nonatomic, strong) NSXMLParser *parser; // 3 - (IBAction)nameChangedAction:(id)sender; // 4 @end  

个interface出现的问题:

类内部自己使用的协议,如不应该在头文件@interface中声明,而应该在类扩展中声明;公开由外部调用的协议,如则写在这儿是正确的。实例变量和IBOutlet不应出现在这儿定义,这将类的内部实现暴露了出去,自从属性可以自动合成后,这里就更应该清凈了。内部使用的属性对象不要暴露在外,应该移动到类扩展中。调用者对IBAction同样不需要关心,那么就不应该放在这儿。

原文网址:https://kknews.cc/culture/n5zr2x3.html

总结

interface 是一个接口,主要是让调用者看的。implementation 里的变数是 private ,是物件导向里的封装原则。

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章