我偶然发现了https://github.com/AlanQuatermain/aqtoolkit/blob/master/Extensions/NSObject%2BProperties.h
接口定义为:
@interface NSObject (AQProperties)
零件有什么(AQProperties)
作用?
我偶然发现了https://github.com/AlanQuatermain/aqtoolkit/blob/master/Extensions/NSObject%2BProperties.h
接口定义为:
@interface NSObject (AQProperties)
零件有什么(AQProperties)
作用?
它被称为“类别”。您可以通过将方法添加到命名类别来扩展现有类,即使您没有它们的源代码:
@interface NSString (MyFancyStuff)
- (NSString*) stringByCopyingStringAndReplacingDollarCharsWithEuros;
- (NSUInteger) lengthIgnoringWhitespace;
@end
然后,您可以像往常一样实现这些新方法
@implementation NSString (MyFancyStuff)
- (NSString*) stringByCopyingStringAndReplacingDollarCharsWithEuros
{
...
}
- (NSUInteger) lengthIgnoringWhitespace
{
...
}
@end
然后,这些新方法的行为类似于以下所有其他方法NSString
(前提是您确实包含了头文件,您在其中声明了类别):
NSString* text = [NSString stringWithFormat: @"Hello, %@", param];
NSUInteger length = [text lengthIgnoringWhitespace];
...
除了作为扩展类的工具(您没有其代码)之外,类别还可用于构建您自己的类的接口。例如:
FancyStuff.h
@interface FancyStuff
// Public methods and properties are declared here
@end
FancyStuff+Protected.h
#import "FancyStuff.h"
@interface FancyStuff (Protected)
// Methods, which may be useful for classes, which derive from
// FancyStuff, but should not be considered part of the public API
@end
FancyStuff.m
#import "FancyStuff+Protected.h"
@implementation FancyStuff
...
@end
@implementation FancyStuff (Protected)
...
@end
它们是类别- 扩展现有类而不继承它们的好方法。
总而言之,您NSObject (AQProperties)
使用NSObject
与AQProperties
.
与子类不同,您只能将方法添加到类别,而不能添加额外的数据成员。