---
title: "Object-C学习（四）"
author: "supermind"
date: "2011-07-14T11:32:33Z"
tags: []
categories: ["移动开发"]
slug: "object-c"
draft: false
lastmod: "2011-07-14T11:32:33Z"
id: 1124167
url: "https://supermind.iteye.com/blog/1124167"
---

引用：http://blog.csdn.net/huanglx1984/article/details/4299965


我们之前说到Objective-C 是一种很好的面向对象的语言，和C++ 和Java 相比，Objective-C 有一些自己独特的东西，下面我们来简单的介绍一下。

 

1）Category 

回想一下，在C++ 中，如果我们想继承一个类，给它添加一些新的功能，我们需要什么？当然是我们需要得到这个类的源代码。但是在Objective-C 中，由于有了这个Category 的概念，我们可以在没有源代码的情况下，为一个已经存在的类添加一些新的功能，比如：

 

// DisplayMath.h


@interface Rectangle(Math) 

- (int) calculateArea;


- (int) calculatePerimeter;


@end 




// DisplayMath.m 

@implementation Rectangle(Math) 

- (int) calculateArea { 

    return width*height;


} 

- (int) calculatePerimeter { 

    return 2*(width+height)


}


@end 

 

这里，使用了之前定义的Rectangle 类，我们想为它添加两个功能：计算面积和周长。即使没有Rectangle 类的源代码，我们也可以通过Category 创建Rectangle 的子类。

使用Category的时候，需要注意两个地方：

1） 只能添加新的方法，不能添加新的数据成员

2）Category 的名字必须是唯一的，比如这里，就不允许有第二个Math 存在。

 

如何使用：

int main( int argc, char* argv ) { 

    Rectangle *rect =  initWithWidth: 5 andHeight:10]; 

    ;


    ;


} 

 


2）如何创建私有方法 

我们知道可以使用@private来声明私有变量，但是如何声明私有方法呢？

Objective-C 中并没有什么关键词来修饰方法，如果我们想让某个方法不被其他的类所见，唯一的方法就是不让这个方法出现在头文件中。比如：

// MyClass.h


#import <Foundation/NSObject.h> 

@implementation MyClass 

- (void) sayHello;


@end 




// MyClass.m 

#import "MyClass.h" 

@implementation MyClass 

- (void) sayHello { 

    NSLog(@"Hello");


}


@end





@interface MyClass(Private) 

- (void) kissGoodbye; 

@end


@implementation MyClass(Private) 

- (void) kissGoodbye { 

    NSLog(@"kissgoodbye");


}


@end 

 

怎么样，看到了Category 的应用么？是的，利用Category 可以方便的实现“私有”方法。

 


3）Protocol 

在Objective-C 中，Protocol 的概念很象Java 中的interface 或者C++ 中的virtual class 。

来看下面这个例子：

@protocol Printing 

- (void) print;


@end 




// MyDate.h 

@interface MyDate: NSObject <Printing> { 

    int year, month, day;


} 

- (void) setDateWithYear: (int)y andMonth: (int)m andDay: (int)d;


@end 




// MyDate.m 

#import <stdio.h> 

#import "MyDate.h" 

@implementation MyDate 

- (void) setDateWithYear: (int)y andMonth: (int)m andDay: (int)d { 

    year = y; 

    month = m; 

    day = d;


} 

- (void) print { 

   printf( "%4d-%2d-%2d", year, month, day );


}


@end 

 

我们首先声明了Printing 协议，任何遵守这个协议的类，都必须实现print 方法。在Objective C 中，我们通过<>来表示遵守某个协议。当某个类声明要遵守某个协议之后，它就必须在.m文件中实现这个协议中的所有方法。

如何使用：

int main( int argc, char* argv ) { 

    MyDate * dat =  init]; 

    ; 

    

    id<Printing> var = dat; 

    ; 




    if(  == YES ) {} // true 





    ;


} 

 

注意两个地方：1）使用id<Printing> 作为类型，而不是象C++中，使用Printing* var; 2）conformsToProtocol 类似于之前所说的respondsToSelector ，用于动态检查某个对象是否遵守某个协议。