【问题标题】:Objective-C String handling issueObjective-C 字符串处理问题
【发布时间】:2012-08-30 12:44:34
【问题描述】:

我正在尝试从 JSON 响应中读取如下内容

{ 
"URL": 
  { 
     "target": "www.google.com", 
    "0": [ 92, 15 ], 
    "1": [ 92, 16 ], 
    "2": [ 74, 15 ], 
    "4": [ 5, 16 ] 
  } 
}

使用 SBJSON 我设法获得了“目标”字段,

testString = [[result objectForKey:@"URL"] objectForKey:@"target"];

当我执行 NSLOG 时,它会显示 www.google.com

但这段代码不适用于其他密钥对。

testString = [[result objectForKey:@"URL"] objectForKey:@"0"];

当我尝试打印 testString 时,它给了我一个错误。

在控制台中我打印了值,它们是,

(lldb) po testString
(NSString *) $4 = 0x0864b190 <__NSArrayM 0x864b190>(
65,
27
)

如何提取这 65 和 27?

【问题讨论】:

    标签: objective-c json nsstring nsarray


    【解决方案1】:

    这是一个对象数组。试试:

    NSArray * array = [[result objectForKey:@"URL"] objectForKey:@"0"];
    id a = [array objectAtIndex:0]; // 65
    id b = [array objectAtIndex:1]; // 27
    
    // now determine the type of objects in the array, and use them appropriately:
    if ([a isKindOfClass:[NSString class]]) {
      NSString * string = a;
      ...use appropriately
    }
    else if ([a isKindOfClass:[NSDecimalNumber class]]) {
      NSDecimalNumber * number = a;
      ...use appropriately
    }
    ...
    else {
      assert(0 && "type not supported");
    }
    

    【讨论】:

    • 我已经尝试过了,但由于某种原因它不起作用:(我得到一个数组对象,但无法通过索引访问它的值。
    • @Sleepwalkerfx 具体是什么原因?
    • 出现此错误 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSDecimalNumber 长度]:当我运行命令“po array”时,无法识别的选择器发送到实例 0x865ab70控制台它显示了一个包含 65 和 27 的数组。
    【解决方案2】:

    这样做:

    if([result objectForKey:@"URL"] objectForKey:@"0"] isKindofClass:[NSArray class])
    {
       NSArray *arritems = [[result objectForKey:@"URL"] objectForKey:@"0"];
       NSMutableArray *values = [NSMutableArray array];
       for( id *item in arritems)
       {
          if([item is isKindOfClass:[NSString class]])
          {
             NSString * valueStr = item; 
             [values addObject:valueStr];
           }
          else if([item is isKindOfClass:[NSDecimalNumber class]])
          {
            NSDecimalNumber * valueNum = item; 
            [values addObject:valueNum];
           }
       } 
       NSLog(@"%@",values);
    }
    

    键值 1 、 2 、 3 的相同逻辑重复

    【讨论】:

    • 在第一行出现错误 *** 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[__NSArrayM stringByReplacingOccurrencesOfString:withString:]:无法识别的选择器发送到实例 0x9b95890'
    【解决方案3】:
    NSArray *data = [[result objectForKey:@"URL"] objectForKey:@"0"];
    

    那么你的物品在[data objectAtIndex:0][data objectAtIndex:1]

    【讨论】:

    • 我收到此错误,` *** 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[NSDecimalNumber length]: unrecognized selector sent to instance 0x865ab70'`
    • 那是因为您将这些对象分配给字符串而不是 id。将它们作为ids 取出,然后简单地根据它们的类型(NSString、NSDecimalNumber 等...)进行操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多