84497517 2016-04-20
Category的用途,在对类不继承的前提下,对类扩展、对类方法的重写。优点是可以不同的程序员写对应的扩展在不同的文件里,然后引用的方式互不干扰,比继承要方便。
栗子:
NSString+URLFormat.h文件:
#import <Foundation/Foundation.h> @interface NSString (URLFormat) - (NSString *)stringByURLFormat:(NSDictionary *)dictionary; @end
NSString+URLFormat.m文件
#import "NSString+URLFormat.h" @implementation NSString (URLFormat) - (NSString *)stringByURLFormat:(NSMutableDictionary *)dictionary{ if([dictionary count]==0) return self; NSMutableString* url = [[NSMutableString alloc] initWithString:self]; [url appendString:@"?"]; NSEnumerator * enumerator = [dictionary keyEnumerator]; id obj; while( obj = [enumerator nextObject]) { NSString* val = [dictionary objectForKey:obj]; NSString* param =(NSString*)obj; if (val) { if(![url hasSuffix:@"?"]){ [url appendFormat:@"&"]; } [url appendFormat:@"%@=%@", param, val]; } } if([url hasSuffix:@"?"]) [url deleteCharactersInRange:NSMakeRange (url.length-1, 1)]; return url; } @end