我正在处理一个应用程序,当我尝试从服务器接收的数据中读取值时,我被阻止。
我有这段代码:
//Item.h
@interface Item : MTLModel <MTLJSONSerializing>
@property (copy, nonatomic) NSNumber *itemId;
@property (copy, nonatomic) NSString *name;
@end
//Item.m
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"itemId" : @"id",
@"name" : @"name"
};
}
以下是我认为错误的代码:
// responseObject is the data received from server using AFNetworking
for (NSDictionary *dict in responseObject) {
Item *myItem = [MTLJSONAdapter modelOfClass:Item.class fromJSONDictionary:dict error:nil];
}
responseObject的架构是:
{
"message": "message",
"success": true,
"item": {
"id": 14576,
"name": "name",
"created_at": 1438245872,
"repeat": false,
"thumb": {
"src": "urlToImage",
"width": 100,
"height": 120
}
}
}
当我运行应用程序时,崩溃消息是
-[NSTaggedPointerString count]: unrecognized selector sent to instance 0xa737365636375737
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString count]: unrecognized selector sent to instance 0xa737365636375737'
我也尝试使用以下句子来获取数据,但在这种情况下,itemId和name是nil:
Item *myItem = [MTLJSONAdapter modelOfClass:Item.class fromJSONDictionary:responseObject error:nil];
所以我有两个问题:我怎样才能做到这一点?而且,我应该如何获得“拇指”的价值?我认为这是一个嵌套的块,我认为这可能会更成问题。
我希望你能帮助我解决这个问题。提前谢谢!
答案 0 :(得分:0)
您必须声明与JSON数据相关的完整密钥路径:
//Item.m
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"itemId" : @"item.id",
@"name" : @"item.name"
};
}
要解析拇指,您可以使用关键路径"item.thumb.src"
。但最好像这样创建单独的类:
//Thumb.h
@interface Thumb : MTLModel <MTLJSONSerializing>
@property (copy, nonatomic) NSURL *src;
@end
//Thumb.m
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"src" : @"src"
};
}
然后使用Item
进行下一次更改:
//Item.h
@interface Item : MTLModel <MTLJSONSerializing>
@property (copy, nonatomic) NSNumber *itemId;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) Thumb *thumb;
@end
//Item.m
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"itemId" : @"item.id",
@"name" : @"item.name"
@"Thumb" : @"item.thumb"
};
}
我希望它有所帮助。