Objective-C 语法四(类别)

来源:互联网 发布:godaddy域名转移 编辑:程序博客网 时间:2024/06/01 19:35

Objective-C 语法四(类别)

首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。

类别是一种为现有的类添加新方法的方式。

1、创建类别

为NSDictionary添加方法toGson,转换成gson字符串。
在新建文件时选择"Objective-C File"。


在File文本框中输入Gson,File Type文本框中选择Category,Class文本框输入NSDictionary。

生成NSDictionary+Gson.h和NSDictionary+Gson.m两个文件。
NSDictionary+Gson.h文件

@interface NSDictionary (Gson)- (NSString*) toGson;@end
NSDictionary+Gson.m文件
@implementation NSDictionary (Gson)- (NSString*) toGson {NSMutableString* gson = [NSMutableString stringWithCapacity: 42];[gson appendString: @"{"];for (id key in self) {[gson appendFormat:@"%@ : \"%@\", ", key, self[key]];}NSUInteger len = [gson length];if (len > 1) {NSRange range = NSMakeRange(len - 2, 2);[gson deleteCharactersInRange: range];}[gson appendString: @"}"];return gson;}@end
main.m文件
#import <Foundation/Foundation.h>#import "NSDictionary+Gson.h"int main(int argc, const char* argv[]) {@autoreleasepool {NSDictionary* dict = @{@"Mike":@"Mike Jordan", @"Tom":@"Tom Lee"};NSLog(@"%@", [dict toGson]);}return 0;} 
类别无法向类中添加新的实例变量。类别方法与现有方法重名时,类别方法具有更高的优先级。

2、类扩展

类扩展是一种特殊的类别,这个类别有以下特点。
  • 不需要名字。
  • 可以添加实例变量。
  • 可以将只读改成可读写的权限。
extension.h文件
@interface Extension : NSObject @property int param1;@property (readonly, assign) int param2;- (void) setParam;@end
extension.m文件
@interface Extension () {int param4;}@property (readwrite, assign) int param2;@property int param3;@end@implementation Extension@synthesize param1;@synthesize param2;@synthesize param3;- (void) setParam {self.param1 = 20;self.param2 = 30;self.param3 = 40;param4 = 50;}- (NSString*) description {return [NSString stringWithFormat: @"(%d %d %d %d)",                      param1, param2, param3, param4];}@end
main.m文件
int main(int argc, const char* argv[]) {@autoreleasepool {Extension* ext = [Extension new];NSLog(@"%@", ext); // (0, 0, 0, 0)[ext setParam];NSLog(@"%@", ext); // (20, 30, 40, 50)}return 0;} 

3、利用类别分散实现代码。

Shape.h文件
@interface Shape {int width, height;int color}@end@interface Shape (ShapeBounds) - (void) setWidth: (int)width andHeight: (int)height;@end@interface Shape (ShapeColor)- (void) setColor: (int)color@end
Shape.m文件
@implementation Shape- (NSString*) description {return [NSString stringWithFormat: @"shape (%d, %d) color = %d",width, height, color]);}@end
ShapeBounds.m文件
#import "Shape.h"@implementation Shape (ShapeBounds)- (void) setWidth: (int)w andHeight: (int)h {width = w;height = h;}@end
ShapeColor.m文件
#import "Shape.h"@implementation Shape (ShapeColor)- (void) setColor: (int)c {color = c;}@end
main.m文件
#import <Foundation/Foundation.h>#import "Shape.h"int main(int argc, const char* argv[]) {@autoreleasepool {Shape* shape = [Shape new];[shape setWidth: 30 andHeight: 40];[shape setColor: 23];NSLog(@"%@", shape);}return 0;}