![](/img/trans.png)
[英]How to configure cellForRowAtIndexPath to handle two different custom UITableViewCell types
[英]Handle object of different types
从我的后端API,我得到一个对象的json,该对象由数组,字典,数字,布尔值,字符串等组成。例如。
{
data:[
{
id : 1,
name : "abcd"
},
{
id : 2,
name : "abcde"
},
{
id : 3,
name : "abcde"
},
]
total_count : 10
}
有时total_count中的值是数字,有时是字符串。 在我的代码中,我已经编码
[lbl setText:[jsonObject valueForKey:@"total_count"]]
由于total_count键值为数字时,这会导致崩溃。 显然我可以做到这一点
[lbl setText:[NSString stringWithFormat:@"%d",[[jsonObject valueForKey:@"total_count"] intValue]]];
但这在API中的很多地方都会发生。 字符串代替了布尔。 data:false
而不是data:[]
[编辑]
[[AFHTTPRequestOperationManager manager] GET:[URLString attachToken] parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
if([[[responseObject valueForKey:@"response"] valueForKey:@"status"] boolValue]) {
NSLog(@"success");
}
if(success)success(operation, **responseObject**);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
if(failure)failure(operation, error);
if(operation.response.statusCode == 0) {
ATAFNetworkingRequestObject *obj = [[ATAFNetworkingRequestObject alloc] init];
obj.urlString = URLString;
obj.paramters = parameters;
obj.successBlock = success;
obj.failureBlock = failure;
obj.type = ATNetworkingRequestGET;
if(![self duplicateRequestExists:obj])[pendingAPICalls addObject:obj];
}
[self logAPIFailedWithOperation:operation parameters:parameters error:error];
} autoRetry:5 retryInterval:7];
在根据您A string is coming instead of a bool. data:false instead of data:[]
之后,您会喜欢A string is coming instead of a bool. data:false instead of data:[]
A string is coming instead of a bool. data:false instead of data:[]
if([datajsonObject isKindOfClass:[NSArray class]]){
//Is array
}else if([datajsonObject isKindOfClass:[NSDictionary class]]){
//is dictionary
}else if([datajsonObject isKindOfClass:[NSString class]])
{
//is String
}
else{
//is something else
}
您可以检查服务器值是数字还是字符串
NSString *newString = [NSString stringWithFormat:@"%@",[[jsonObject valueForKey:@"total_count"]
if ([newString isKindOfClass:[NSNumber class]])
{
NSLog(@"It is number");
}
if ([newString isKindOfClass:[NSString class]])
{
NSLog(@"It is string");
}
SWIFT代码 :
lblCount.text = String(datajsonObject["total_count"] as AnyObject)
目标c:
NSString *strCount = [NSString stringWithFormat:@"%@",[jsonObject valueForKey:@"total_count"]]
if ([strCount isKindOfClass:[NSString class]])
{
// Write your code to show on label
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.