赞
踩
首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。
类别是一种为现有的类添加新方法的方式。假如为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;
}
输出
{Tom : "Tom Lee", Mike : "Mike Jordan"}
类别无法向类中添加新的实例变量。类别方法与现有方法重名时,类别方法具有更高的优先级。
类扩展是一种特殊的类别,这个类别有以下特点。
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;
}
输出
(0 0 0 0)
(20 30 40 50)
Shape.h
文件
@interface Shape : NSObject { 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 alloc] init];
[shape setWidth:30 andHeight:40];
[shape setColor:23];
NSLog(@"%@", shape);
}
return 0;
}
输出
shape (30, 40) color = 23
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。