Some learning of Objective-c 3 Category

The purpose of Category is to extend the class and rewrite the class method without inheriting the class. The advantage is that different programmers can write corresponding extensions in different files, and then the reference methods do not interfere with each other, which is more convenient than inheritance.

Chestnut:

NSString+URLFormat.h file:
#import <Foundation/Foundation.h>

@interface NSString (URLFormat)

- (NSString *)stringByURLFormat:(NSDictionary *)dictionary;

@end



NSString+URLFormat.m file
#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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326980138&siteId=291194637