且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective-C中的类别用法

更新时间:2022-11-22 18:09:40

不是"private"这个名字使它成为私有的.这些方法是私有的,因为它们在实现文件中声明的类别中.

It isn't the name "private" that makes it private; the methods are private because they are in a category declared within the implementation file.

类别有三种用途,每种用途都将方法添加到类中(注意:仅方法,而不是iVars)

There are three uses of a category, each of which add methods to a class (note: methods only, not iVars)

扩展现有的可可类

这使您可以将自己的方法添加到现有类中. 例如,如果要扩展NSString以应用大写字母,则可以创建一个名为NSString + Capitals的新类.在NSString + Capitals.h中,您将拥有:

This lets you add your own methods to an existing class. For example, if you want to extend NSString to apply special capitalization, you could create a new class called, say NSString+Capitals. in the NSString+Capitals.h you would have:

@interface NSString (Capitals)

-(NSString *)alternateCaps:(NSString *)aString;

@end

,然后在NSString + Capitals.m中实现该方法

and in NSString+Capitals.m you would implement the method

@implementation NSString (Capitals)
-(NSString *)alternateCaps:(NSString *)aString
{
    // Implementation
}

类的私有方法

与上面的相同,除了额外的方法是在实现文件(.m)中声明和定义的,通常是一种拥有私有方法的方法-因为它们不在.h文件中(这是一个#由其他类导入),它们根本不可见.在这种情况下,方法的实现是在其自己的实现模块中完成的.例如

This is the same as above, except that the extra methods are declared and defined in the implementation file (.m) Usually a way of having private methods - because they are not in the .h file (which is the one #imported by other classes) they are simply not visible. In this case, the implementation of the methods are done in their own implementation block. e.g

// someClass.m
@interface someClass (extension)
-(void)extend;
@end

@implementation someClass
    // all the methods declared in the .h file and any superclass
    // overrides in this block
@end

@implementation someClass (extension)
-(void)extend {
    // implement private method here;
}

类扩展(10.5豹的新增功能)

Class Extension (New for 10.5 Leopard)

拥有私有方法的一种更简单的方法.在这种特殊情况下,类别名称为空,私有方法与所有其他类方法在同一块中实现.

A simpler way of having private methods. In this special case, the category name is empty and the private methods are implemented in the same block as all the other class methods.

// someClass.m
@interface someClass ()
-(void)extend;
@end

@implementation someClass
    // all the methods declared in the .h file and any superclass
    // overrides in this block
    // Implement private methods in this block as well.
-(void)extend {
    // implement private method here;
}

@end

这是一个链接有关类别和扩展名的Apple文档.

Here's a link to the Apple docs on Categories and extensions.