使用 NSURLComponents 和 NSURLQueryItem 来进行更规范的 URL 字符串拼接

本文介绍如何使用 Objective-C 中的 NSURLComponents 和 NSURLQueryItem 类来构建复杂的 URL 字符串,这种方法使得代码更加整洁易维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常的编程工作中,经常需要拼接URL字符串,可能直接写成如下的形式:

NSString *urlStr = @"https://www.demo.com/query?name=Jack";
复制代码

对于比较简短的url字符串,这种写法直观方便。但是如果需要拼接一大串的query语句的话,就会非常地长(虽然Objective-C语法本身也是非常的长),譬如:

NSString *urlStr = 
[NSString stringWithFormat:@"https://www.demo.com/query?name=%@&gender=%@&lng=%@&lat=%@&age=%@", @"Jack", @"male", @"121", @"31", @"20"];
复制代码

此时如果你的显示器不是特别宽的话,应该已经自动换行了,并且占位符也比较多,看起来比较乱,后续维护也会比较麻烦。 此时可以使用NSURLComponentsNSURLQueryItem来进行拼接:

NSURLComponents *components = [NSURLComponents componentsWithString:@"https://www.demo.com/query"];
NSMutableArray<NSURLQueryItem *> *queryItems = @[].mutableCopy;
NSURLQueryItem *nameItem = [NSURLQueryItem queryItemWithName:@"name" value:@"Jack"];
NSURLQueryItem *genderItem = [NSURLQueryItem queryItemWithName:@"gender" value:@"male"];
NSURLQueryItem *lngItem = [NSURLQueryItem queryItemWithName:@"lng" value:@"121"];
NSURLQueryItem *latItem = [NSURLQueryItem queryItemWithName:@"lat" value:@"31"];
NSURLQueryItem *ageItem = [NSURLQueryItem queryItemWithName:@"age" value:@"20"];
[queryItems addObject:nameItem];
[queryItems addObject:genderItem];
[queryItems addObject:lngItem];
[queryItems addObject:latItem];
[queryItems addObject:ageItem];
components.queryItems = queryItems;

NSURL *url = components.URL;
...

复制代码

这样写就比较清晰,并且后期维护起来也相对容易些,当然你也可以用字典简单封装一下NSURLQueryItem数组(在绝大多数的场景中适用):

- (NSArray<NSURLQueryItem *> *)queryItemsWithParameters:(NSDictionary<NSString *, NSString *> *)dict {
    if ([dict isKindOfClass:[NSDictionary class]] && [dict count] > 0) {

        NSMutableArray<NSURLQueryItem *> *arrM = @[].mutableCopy;
        for (NSString *keyStr in dict.allKeys) {
            NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:keyStr value:dict[keyStr]];
            [arrM addObject:item];
        }
        return arrM;
    }

    return nil;
}



    NSDictionary *dict = @{@"name": @"Jack",
                           @"gender": @"male",
                           @"lng": @"121",
                           @"lat": @"31",
                           @"age": @"20"};
                    
    components.queryItems = [self queryItemsWithParameters:dict];                           

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值