网络:自定义模型转 JSON

#import "ViewController.h"
#import "Person.h"
#import "NSObject+PropertyList.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
// initWithDict

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    Person *person = [[Person alloc]init];
    person.name = @"张三";
    person.age = 20;

    // kvc可以给私有的属性赋值
    // 只读
    [person setValue:@"广州" forKey:@"address"];
    // 只读属性
//    person.phone = @"13800138000";
    [person setValue:@"1388" forKey:@"phone"];

    // 字典 dictionaryWithValuesForKeys 返回对象字典
    NSDictionary *dict = [person dictionaryWithValuesForKeys:[Person propertys]];
//    NSDictionary *dict = [person dictionaryWithValuesForKeys:@[@"address",@"phone"]];

    // 二进制数据
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];

    // NSURL
    NSURL *url = [NSURL URLWithString:@"http://localhost/post/postjson.php"];
    // NSURLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // POST
    [request setHTTPMethod:@"POST"];
    // Body
    [request setHTTPBody:data];
    // NSURLConnection
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];

}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值