【问题标题】:Accessing array's contents iOS 6访问数组的内容 iOS 6
【发布时间】:2013-02-23 14:17:03
【问题描述】:

我是编码新手,想知道是否有人可以帮助我。我是第一次使用网络服务。我在访问任何数组时都遇到了麻烦。我什么都弄不出来。

现在我可以成功地从 Web 服务获取信息并将其存储在 NSArray 中。我 NSLog 它并看到内容出现在我的控制台中。我检查了数组的计数,它是 5。

但我无法访问任何内容。错误状态:CustomTableView[4083:11303] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xff231b0

我真的很想知道如何访问数组中的各种值。在此先感谢您的帮助! :)

@property (strong, nonatomic) NSArray *searchedYummlyRecipeList;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.searchedYummlyRecipeList = [NSJSONSerialization JSONObjectWithData:self.yummlyRecipesData options:nil error:nil];
    //test logging
    NSLog(@"Recipe List: %@ ", self.searchedYummlyRecipeList);//prints fine
    NSLog(@"Count of test array: %lu", (unsigned long)[self.searchedYummlyRecipeList count]);//prints fine 
    NSArray *testArray = [[self.searchedYummlyRecipeList objectAtIndex:1]objectForKey:@"criteria"];//breakpoint is here
    NSLog(@"test Array: %@", testArray);//doesn't get here
    NSLog(@"test Array count: %lu", (unsigned long)[testArray count]);//doesn't get here

}

nslog 输出摘录:

 Recipe List: {
attribution =     {
    html = "<a href='http://www.yummly.com/recipes/onion-soup'>onion soup recipes</a> search powered by <img src='http://static.yummly.com/api-logo.png'/>";
    logo = "http://static.yummly.com/api-logo.png";
    text = "onion soup recipes: search powered by Yummly";
    url = "http://www.yummly.com/recipes/onion-soup";
};
criteria =     {
    allowedIngredients =         (
    );
    excludedIngredients =         (
    );
    facetFields =         (
    );
    maxResults = 6;
    requirePictures = 0;
    resultsToSkip = 0;
    terms =         (
        onion,
        soup
    );
};
facetCounts =     {
};
matches =     (
            {
        attributes =             {
            course =                 (
                Soups,
                Appetizers
            );
            cuisine =                 (
                French
            );
            holiday =                 (
                Thanksgiving
            );
        };
        flavors =             {
            bitter = "0.1666666666666667";
            meaty = "0.1666666666666667";
            piquant = 0;
            salty = "0.1666666666666667";
            sour = "0.1666666666666667";
            sweet = "0.1666666666666667";
        };
        id = "French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364";
        ingredients =             (
            "beef broth",
            "minced garlic",
            "stick butter",
            "yellow onion",
            "french bread",
            "worcestershire sauce",
            "gruyere cheese",
            "low sodium chicken broth",
            "dry white wine"
        );
        rating = 0;
        recipeName = "French Onion Soup";
        smallImageUrls =             (
            "http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
            "http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
            "http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
        );
        sourceDisplayName = "The Pioneer Woman";
        totalTimeInSeconds = 0;
    },
            {
        attributes =             {
            course =                 (
                "Main Dishes"
            );
        };
        flavors =             {
            bitter = 1;
            meaty = "0.1666666666666667";
            piquant = 0;
            salty = 1;
            sour = "0.1666666666666667";
            sweet = "0.3333333333333333";
        };
        id = "Awesome-Slow-Cooker-Pot-Roast-Allrecipes";
        ingredients =             (
            "onion soup mix",
            "condensed cream of mushroom soup",
            "pot roast",
            water
        );
        rating = "4.69";
        recipeName = "Awesome Slow Cooker Pot Roast";
        smallImageUrls =             (
            "http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
            "http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
        );
        sourceDisplayName = AllRecipes;
        totalTimeInSeconds = 29400;
    },
            {
        attributes =             {
            course =                 (
                Soups
            );
        };
        flavors =             {
            bitter = "0.1666666666666667";
            meaty = "0.1666666666666667";
            piquant = "0.6666666666666666";
            salty = "0.1666666666666667";
            sour = "0.1666666666666667";
            sweet = "0.1666666666666667";
        };
        id = "Chicken-Soup-for-Knaidelach-The-Shiksa-Blog-48854";
        ingredients =             (
            "sea salt",
            "bay leave",
            onions,
            giblets,
            "fresh dill",
            "curly-leaf parsley",
            "whole cloves",
            "chopped leaves",
            "black peppercorns",
            carrot
        );
        rating = 0;
        recipeName = "Chicken Soup for Knaidelach";
        smallImageUrls =             (
            "http://i.yummly.com/Chicken-Soup-for-Knaidelach-The-Shiksa-Blog-48854-10792.s.png",
            "http://i.yummly.com/Chicken-Soup-for-Knaidelach-The-Shiksa-Blog-48854-10711.s.png",
            "http://i.yummly.com/Chicken-Soup-for-Knaidelach-The-Shiksa-Blog-48854-10617.s.png"
        );
        sourceDisplayName = "The Shiksa in the Kitchen";
        totalTimeInSeconds = 10800;
    },
            {
        attributes =             {
            course =                 (
                Soups
            );
            cuisine =                 (
                American
            );
        };
        flavors = "<null>";
        id = "Chicken-Soup-The-Pioneer-Woman-200156";
        ingredients =             (
            ribs,
            carrots,
            chicken,
            "bay leaf",
            salt,
            parsnips,
            "black pepper",
            onion,
            "chicken broth"
        );
        rating = 0;
        recipeName = "Chicken Soup";
        smallImageUrls =             (
            "http://i.yummly.com/Chicken-Soup-The-Pioneer-Woman-200156-39944.s.png"
        );
        sourceDisplayName = "The Pioneer Woman";
        totalTimeInSeconds = 0;
    },

【问题讨论】:

    标签: json api ios6 nsarray nsdictionary


    【解决方案1】:

    "[__NSCFDictionary objectAtIndex:]: unrecognized selector" 告诉您“objectAtIndex”选择器(方法)被“发送”到(调用)一个 NSDictionary 对象。但是objectAtIndex不是NSDictionary的方法,所以报错。

    不清楚您试图访问什么“数组”,但它不是数组,它是一个“字典”——一个键->值映射对象。您可以使用“objectForKey”来访问它。

    请注意,在 Objective-C 中很容易将错误的类型放入变量中。仅仅因为一个变量的类型是“NSArray*”并不意味着它真的是一个 NSArray——例如,你可以从 JSON 解析器中得到一个字典而不是一个数组(因为这就是 JSON “所说”的内容)。

    在您上面的列表中,“searchedYummlyRecipeList”绝对是一个 NSDictionary——NSLog 中的 {} 字符表明了这一点。 (数组将被 () 包围。)

    【讨论】:

    • 嗨热舔。感谢您的回答,非常感谢。我已经按照建议剥离了。我现在正在尝试获取配方名称,但似乎无法设置单元格的文本。我不知道为什么?你有什么建议吗?
    • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"searchedRecipeCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; NSDictionary *criteria = [self.searchedYummlyRecipeList[@"matches"]objectAtIndex:0]; NSString *string = [criteria objectForKey:@"recipeName"]; NSLog(@"这是来自单元格的字符串:%@", string); cell.textLabel.text = 字符串; //返回配置的单元格 return cell; }
    • 将您的 JSON(不是上面的 NSLog 输出)粘贴到 this page 中,它会以很好的格式显示它,因此更容易理解。 “matches”包含(接近我可以解码)一个数组,其中的元素包含“attributes”、“flavors”、“id”、“ingredients”、“rating”、“recipeName”、“smallImageUrls”、“sourceDisplayName”和“总时间秒数”。如果你得到 recipeName 字符串 OK,那么你的 UI 代码有问题,你需要发布它。
    • 当我 nslog 我得到空值。我在其他方法中添加了 nslog。看来 cellForRowAtIndexPath: 发生在 connection:didReceiveData: 之前。所以我添加了一个刷新按钮。但即使按下它,我仍然看不到输出。
    • - (IBAction)refreshRecipe:(id)sender { NSDictionary *criteria = [self.searchedYummlyRecipeList[@"matches"]objectAtIndex:0]; NSString *string = [criteria objectForKey:@"recipeName"]; NSLog(@"这是刷新配方中单元格中的字符串:%@", string); [self.searchedRecipeTableView reloadData]; }
    【解决方案2】:

    看起来你的食谱列表是一个字典,而不是一个数组。 'criteria' 键的值也是一个字典(恰好包含一些数组值的字典)。

    要获取标准字典,您可以这样做:

    NSDictionary *criteria = self.searchedYummlyRecipeList[@"criteria"];
    

    你当然也应该修正你的@property 声明:

    @property (strong, nonatomic) NSDictionary *searchedYummlyRecipeList;

    编辑

    因此,为了进一步从标准字典中获取值,您可能会这样做:

    NSNumber *maxResults = criteria[@"maxResults"];

    或者,您可以使用键路径来获取特定值:

    NSString *url = [self.searchedYummlyRecipeList valueForKeyPath:@"attribution.url"];

    另一方面,Matches 是一个数组。如果要查看第一个匹配,例如:

    NSArray *matches = self.searchedYummlyRecipeList[@"matches"];
    NSDictionary *firstMatch = matches[0];
    NSString *firstMatchID = firstMatch[@"id"];
    

    【讨论】:

    • 请注意,上面带有[] 的符号是最新编译器的新功能。对于 NSDictionary,它(在编译器内部)转换为“objectForKey”调用。尽管新符号很方便,但理解底层实现也很重要。
    • Firoze 非常感谢。我已将其更改为 NSDictionary,现在可以获取标准。非常感激。你是救生员!但是我的问题有点笼统。你知道我如何获得价值吗?例如,为了参数,我将如何进一步深入了解让我们说“maxResults”或匹配“cuisine”。
    • 在我 nslog 时您推荐的更改后,我的输出是:stackoverflow 后的测试数组:{ allowedIngredients = ( );排除成分 = ( );方面字段 = ( );最大结果 = 6;要求图片= 0;结果跳过 = 0;条款=(洋葱,汤);以防万一你好奇。 :)
    • @Anthony - 我喜欢说“剥洋葱”。钻入一个级别,NSLog 你必须确保它是预期的,然后进行下一个级别的访问。假设这是一个类似 JSON 的结构,您在每个级别都有一个数组 (()) 或字典 ({}) 或一个简单的字符串/数字。剥去层,直到你得到你想要的。
    猜你喜欢
    • 2014-03-05
    • 2022-07-26
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2014-05-18
    相关资源
    最近更新 更多