网络:JSONKit框架的使用(天气预报)

本文通过实际代码示例对比了使用第三方库JSONKit与iOS系统自带的JSON解析功能在性能上的差异,并建议在旧项目中将第三方库替换为系统自带的方法以提高效率。

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

#import "ViewController.h"
#import "JSONKit.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
}

/**
 1. 使用系统的解析json 效率明显比 jsonkit 会快,而且快很多
 2. 如果旧项目中遇到使用解析json的第三方框架,尽量改成用系统的(AFNetworking 也是使用系统的)
 3. 如果修改,可以按以下步骤:
    3.1 删除JSONKit.h 和 JSONKit.m
    3.2 哪里出错改哪里

 */
- (void)JSONKit {
    NSURL *url = [NSURL URLWithString:@"http://localhost/demo.json"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:0 timeoutInterval:10];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
        for (int i = 0; i< 100 * 1000; i++) {
            id result = [[JSONDecoder decoder] objectWithData:data];
        }
         NSLog(@"jsonkit %f",CFAbsoluteTimeGetCurrent() - start);
    }];
}

- (void)loadData {
    NSURL *url = [NSURL URLWithString:@"http://localhost/demo.json"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:0 timeoutInterval:10];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
        for (int i = 0; i< 100 * 1000; i++) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        }
        NSLog(@"jsonkit %f",CFAbsoluteTimeGetCurrent() - start);
    }];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值