请考虑以下代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSURL *url = [NSURL URLWithString:@"http://localhost/faq.php?faqType=2"]; // Modify this to
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url]; // Pulls the URL
NSLog(@"jsonreturn=%@",jsonreturn); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary *dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rows = [[dict objectForKey:@"faq"] retain];
}
[jsonreturn release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell.
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict1 = [rows objectAtIndex:indexPath.row];
NSLog(@"%@", dict1);
cell.textLabel.text = [dict1 objectForKey:@"faqQues"];
}
//if it is not getting NULL value then UItableView is ok
{"faq":[{"faqQues":"this is mr.mack?"},{"faqQues":"is he good man?"}]}
//but if the data is like NULL
{"faq":[{"faqQues":"this is mr.mack?"},{"faqQues":null}]} // then it is creating EXEC_BAD_ACCESS error,
那么如何避免NULL或检查空值,或者我该如何解决这个问题呢?
答案 0 :(得分:2)
您可以在使用之前查询该值。
if ([dict objectForKey:@"faqQues"] == [NSNull null]) {
// value is null, use your own value here
} else {
// good value to use
}
您也可以在枚举时执行此操作。
for (id value in dict) {
if (value == [NSNull null]) {
// null
}
}
答案 1 :(得分:0)
TouchJSON的文档声明,JSON空值使用NSNull单例表示(通常用于表示集合中的nil - 不允许使用nil)。所以你必须检查[NSNull null]。
但TouchJSON允许覆盖默认的空对象:
CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer];
theDeserializer.nullObject = NULL;
详细信息https://github.com/TouchCode/TouchJSON(请参阅“在输出中避免NSNull值。”部分)
答案 2 :(得分:0)
我的同事程序员康拉德克莱默实际上想出了这个:https://gist.github.com/3362607
我会将其更改为函数并用@“”
替换NULL值