在iOS中存储服务器响应的位置?

时间:2016-01-10 20:47:44

标签: ios objective-c

我向服务器发出GET请求以获取JSON数据:

{
name: 'http://placehold.it/32x32',
age: '20',
social: {
  id: '1',
  count: '3',
  shares: '3'
}
}

将此数据存储在TableView中显示后的变量中的最佳方法是什么? 我应该为每个JSON密钥创建@property吗? 或者创建一个对象NSDictionary

1 个答案:

答案 0 :(得分:0)

我最早会创建一个具有这些属性的类/结构。 像这样:

<强> SWIFT

class myClass {

    var name: String?
    var age: Int?
    var id: Int?
    var count: Int?
    var shares: Int?

    init(dictionary: [String:AnyObject]) {
        name = dictionary["name"] as? String
        age = dictionary["age"] as? Int

        if let social = dictionary["social"] as? [String:AnyObject] {
            id = social["id"] as? Int
            count = social["count"] as? Int
            shares = social["shares"] as? Int
        }
    }
}

然后,当您获得数据时,您可以像这样创建对象。

let myObject = myClass(dictionary: jsonDictionary)

Objective-C基本相同:

<强>目的-C

@property (nonatomic) NSString *name;
@property (nonatomic) NSInteger age;
@property (nonatomic) NSInteger socialID;
@property (nonatomic) NSInteger count;
@property (nonatomic) NSInteger shares;

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    if ((self = [self init])) {
        _name = dictionary[@"name"]
        _age = [[dictionary valueForKey:@"age"] integerValue] 

        NSDictionary *social = dictionary[@"social"]
        _socialID = [[social valueForKey:@"id"] integerValue]
        _count = [[social valueForKey:@"count"] integerValue]
        _shares = [[social valueForKey:@"shares"] integerValue]
    }
}