您的位置:首页 > 编程语言 > Go语言

Category Extension

2016-03-26 10:20 344 查看
Categories Add Methods to Existing Classes

如果你需要向现有的类中添加一个方法,最简单的方式是使用Category

[1]Category

1.语法

使用@interface声明一个category,不需要指明任何继承,但需要在括号中指明category的名字。

例如:

@interface ClassName (CategoryName)

@end

注意:(1)你可以为任何一个类声明一个分类,即使你没有原始实现的源代码。你在类别中声明的任何方法对于原始类的所有实例都可以使用(At runtime, there’s no difference between a method added by a category and one that is implemented by the original class.)

(2)Once you’ve declared a category and implemented the methods, you can use those methods from any instance of the class, as if they were part of the original class interface

例子:一个XYZPerson类,有一个人的first name、 last name。你需要频繁地显示他们。为了不用每次写代码获得first name、 last name。你可以为XYZPerson类增加一个分类。一个分类通常被声明在一个单独的.h文件中,而实现在另外的源代码文件中。在XYZPerson中,你在.h文件中声明的分类叫做XYZPerson+XYZPersonNameDisplayAdditions.h。(使用分类时需要导入分类的头文件)

头文件

import “XYZPerson.h”

@interface XYZPerson (XYZPersonNameDisplayAdditions)

(NSString *)lastNameFirstNameString;

@end

//例子中XYZPersonNameDisplayAdditions分类定义了一个返回需要的字符串的额外的方法。

实现:

import “XYZPerson+XYZPersonNameDisplayAdditions.h”

@implementation XYZPerson (XYZPersonNameDisplayAdditions)

(NSString *)lastNameFirstNameString {

return [NSString stringWithFormat:@”%@, %@”, self.lastName, self.firstName];

}

@end

2.category使用

(1)use categories to split(分离)the implementation of a complex class across multiple source code files.

(2)to provide different implementations for the category methods, depending on whether you were writing an app for OS X or iOS.

3.限制

在分类中不能声明额外的实例变量

[2]Extension扩展

Class Extensions Extend the Internal Implementation

1.介绍: A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the @implementation block for the original class so you can’t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.

头文件

例1:@interface ClassName ()

@end

//因为括号中没有名字,所以extension进程称为匿名分类

例2:类扩展能增加自己的属性和实例

@interface XYZPerson ()

@property NSObject *extraProperty;

@end

2.使用使用类扩展去隐藏私有信息

例如XYZPerson中可能有一个uniqueIdentifier的属性,用来记录社保号的信息,给一个人分配一个社保号可能需要大量的工作,因此XYZPerson需要又一个readonly属性。而且提供一些方法。

@interface XYZPerson : NSObject



@property (readonly) NSString *uniqueIdentifier;

(void)assignUniqueIdentifier;

@end

//这意味着uniqueIdentifier是不能改变的,如果一个人没有社保号,就调用- (void)assignUniqueIdentifier方法来获得。

为了XYZPerson类能内部的改变这个属性,它需要在类扩展中重新定义这个属性,即在implementation文件上方

@interface XYZPerson ()

@property (readwrite) NSString *uniqueIdentifier;

@end

@implementation XYZPerson



@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: