从一个数组元素中分离两个字符串

时间:2013-04-28 18:15:57

标签: ios objective-c json nsstring nsarray

我想知道是否有人可以提供一些帮助。基本上我正在调用一个Web服务,然后尝试获取大型托管图像URL。 Web服务的输出是这样的:

images =     (
                {
            hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
            hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
        }
    );

主要的问题是当我认为它们应该在2中时,两个字符串只在我的一个数组元素中。而且我不是100%但可能它们可能是字典:-S我只是不是当然。我的代码如下:

    NSArray *imageArray = [[NSArray alloc]init];
    imageArray = [self.detailedSearchYummlyRecipeResults objectForKey:@"images"];
    NSLog(@"imageArray: %@", imageArray);
    NSLog(@"count imageArray: %lu", (unsigned long)[imageArray count]);
    NSString *hostedLargeurlString = [imageArray objectAtIndex:0];    
    NSLog(@"imageArrayString: %@", hostedLargeurlString);

上面代码中的输出(nslog)是:

2013-04-28 18:59:52.265 CustomTableView[2635:11303] imageArray: (
        {
        hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
        hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
    }
)
2013-04-28 18:59:52.266 CustomTableView[2635:11303] count imageArray: 1
2013-04-28 18:59:52.266 CustomTableView[2635:11303] imageArrayString: {
    hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
    hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}

有没有人知道如何将one元素分别分为hostedlargeUrl和hostedsmallUrl?

非常感谢您提供的任何帮助!

3 个答案:

答案 0 :(得分:0)

看起来像一个数组中的数组,所以

NSArray* links = [self.detailedSearchYummlyRecipeResults objectForKey:@"images"];
NSString* bigLink = [links objectAtIndex:0];
NSString* smallLink = [links objectAtIndex:1];

或者它可以是字典

NSDictionary* links = [self.detailedSearchYummlyRecipeResults objectForKey:@"images"];
    NSString* bigLink = [links objectForKey:@"hostedLargeUrl "];
    NSString* smallLink = [links objectForKey:@"hostedSmallUrl "];

您可以通过打印出类名

来查看对象的类
NSLog(@"Class Type: %@", [[self.detailedSearchYummlyRecipeResults objectForKey:@"images"] class]);

答案 1 :(得分:0)

实际上,images数组包含一个字典

images = ( 
        {
          hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
          hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
        }
);

所以:

NSDictionary *d = [self.detailedSearchYummlyRecipeResults objectForKey:@"images"][0];
NSString *largeURL = d[@"hostedLargeUrl"];
NSString *smallURL = d[@"hostedSmallUrl"];

答案 2 :(得分:0)

[imageArray objectAtIndex:0]的值是NSDictionary。您错误地将其指定为NSString。您需要以下内容:

  NSDictionary *hostedLarguerDictionary =
    (NSDictionary *) [imageArray objectAtIndex:0];

然后访问'大网址'使用:

   hostedLarguerDictionary[@"hostedLargeUrl"]

或等同于

   [hostedLarguerDictionary objectForKey: @"hostedLargeUrl"];