2011-12-01 83 views
0

请考虑下面的代码:如何避免在目标C NULL值

- (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或检查空值,或者如何解决这个问题?

回答

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 
    } 

} 
0

TouchJSON状态的文档,即JSON空值使用NSNull单表示(通常用于表示集合零 - ,其中零是不允许的)。所以你必须检查[NSNull null]。

但TouchJSON允许覆盖默认空对象:(“输出避免NSNull值”见一节)

CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer]; 
theDeserializer.nullObject = NULL; 

详细https://github.com/TouchCode/TouchJSON