Objective-c 的一些学习3 Category
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
相关推荐
84407518 2012-07-16
87214552 2015-10-27
84407518 2016-01-25
89283517 2012-06-19
ObjectiveC 2012-06-14
zhujiangtaotaise 2020-01-01
AllenG 2013-07-07
Beatopcoder 2013-07-14
afrtooylsw 2014-05-14
让编程改变世界 2015-03-13
shqhope 2015-04-09
zoutian00 2015-05-12
huangshm 2019-01-14
86981633 2019-06-29
我的iOS王者之路 2019-06-28
好好学习天天 2019-06-28