【问题标题】:Fill UITableView with dictionary from JSON Request iOS用来自 JSON Request iOS 的字典填充 UITableView
【发布时间】:2014-05-17 23:30:15
【问题描述】:

我现在的问题是我在这段代码中有数组。

需要将 UItableView 替换为 URL Request JSON 响应 Object 并替换 Dictionary Values。

有一种方法可以清理信息并重新加载表以刷新新数据或可以方便地实现此目的的方法吗?

#import "RecipeTableViewController.h"
#import "RecipeTableCell.h"
#import "RecipeDetailViewController.h"
#import "Recipe.h"

@interface RecipeTableViewController ()

@end

@implementation RecipeTableViewController
{
    NSArray *recipes;
    NSArray *searchResults;

    NSMutableArray *myObject;
    // A Dictionary Object
    NSDictionary *dictionary;

    NSString *name;
    NSString *subject;
    NSString *avatar;
    NSString *rate;
    NSString *bio;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    name = @"name";
    subject = @"subject";
    avatar = @"avatar";
    rate = @"rate";
    bio = @"bio";

    myObject = [[NSMutableArray alloc] init];
    NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://latamig.com/data.json"]];

    id jsonObjects = [NSJSONSerialization JSONObjectWithData: jsonSource options:NSJSONReadingMutableContainers error:nil];


    for (NSDictionary *dataDict in jsonObjects)
    {
        NSString *name_data = [dataDict objectForKey:@"name"];
        NSString *subject_data = [dataDict objectForKey:@"subjects"];
        NSString *avatar_data = [dataDict objectForKey:@"avatar_s"];
        NSString *rate_data = [dataDict objectForKey:@"user_rate"];
        NSString *bio_data = [dataDict objectForKey:@"bio"];

        NSLog(@"Name: %@", name_data);
        NSLog(@"Subject: %@",subject_data);
        NSLog(@"Avatar: %@", avatar_data);
        NSLog(@"Rate: %@",rate_data);
        NSLog(@"Bio: %@",bio_data);

        dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                      name_data,name,
                      subject_data,subject,
                      avatar_data,avatar,
                      rate_data,rate,
                      bio_data, bio, nil];

        [myObject addObject:dictionary];
    }



    // API CALL MAKE END

    /* Initialize the recipes array
    Recipe *recipe1 = [Recipe new];
    recipe1.name = @"Andruw";
    recipe1.prepTime = @"$255/h";
    recipe1.bio = @"I'm a Web developer working for 3 years as a Programmer on Facebook";
    recipe1.image = @"avatar1.jpg";


    recipes = [NSArray arrayWithObjects:recipe1, nil];

     */



}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];

    } else {
        return [recipes count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 71;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableCell";
    RecipeTableCell *cell = (RecipeTableCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    if (cell == nil) {
        cell = [[RecipeTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Display recipe in the table cell
    Recipe *recipe = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        recipe = [searchResults objectAtIndex:indexPath.row];
    } else {
        recipe = [recipes objectAtIndex:indexPath.row];
    }

    cell.nameLabel.text = recipe.name;
    cell.bioLabel.text = recipe.bio;
    cell.thumbnailImageView.image = [UIImage imageNamed:recipe.image];
    cell.thumbnailImageView.clipsToBounds = YES;
    cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width /2;
    cell.prepTimeLabel.layer.cornerRadius = 5;
    cell.prepTimeLabel.text = recipe.prepTime;

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = nil;
        Recipe *recipe = nil;

        if (self.searchDisplayController.active) {
            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
            recipe = [searchResults objectAtIndex:indexPath.row];
        } else {
            indexPath = [self.tableView indexPathForSelectedRow];
            recipe = [recipes objectAtIndex:indexPath.row];
        }

        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipe = recipe;
    }
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
    searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}


@end

【问题讨论】:

  • 据我所知,Xcode 没有处理 JSON 的特殊工具。
  • (您的意思是 iOS 还是 OSx?)
  • 这个问题似乎是题外话,因为它不是一个问题。
  • 也许如果您改写并清楚地将您的问题表述为“我如何...”或“为什么这会引发错误...”等,我们可以更好地回答您的问题。此外,如果您可以将代码示例隔离到较小的部分,而不是发布整个视图控制器。这会让事情变得更容易。
  • Eddwin,您的问题有点不清楚。最好的办法是查看这方面的众多教程之一...nscookbook.com/2013/03/… ..提示请务必只查看最近的教程,因为今天,在 iOS 中使用 JSON 非常容易。 (在过去你必须使用图书馆等)

标签: ios json uitableview


【解决方案1】:

不清楚您在问什么,但这些代码片段可能会有所帮助:

@property (nonatomic, strong) NSData *rawFromCloud;

#define yourUrl [NSURL URLWithString:@"http://blah.com/json/stubs"]

-(void)fromCloud:(void(^)(void))after
    {
    dispatch_async(dispatch_get_main_queue(),
        ^{
        self.rawStubsFromCloud = [NSData dataWithContentsOfURL:yourUrl];
        after();
        });
    }

NSError* error;
NSDictionary* jdic = [NSJSONSerialization
    JSONObjectWithData:self.rawFromCloud
    options:kNilOptions
    error:&error];

//CRITICAL -- do this, to see what is going on:
NSLog(@"%@", jdic); //to see the fields available

NSArray* stubs = [jdic objectForKey:@"stubs"];

就是这样 - 你有一个数组!

for ( NSDictionary *stub in stubs )
    {
    NSString *nn = [stub objectForKey:@"userName"];
    NSLog("one userName %@", nn);
    }

(脚注,你也有“新”语法存根[@“userName”],但我认为'objectForKey'语法对初学者来说更容易。干杯,希望它有所帮助。)

【讨论】:

  • 嘿@Leo! 有点不清楚,也不是完全不清楚。我认为可以肯定的是:Eddwin 只是对如何采用“名称”:[] 类型的字段并用它填充 NSArray 感到困惑。如果是这样,上面应该为他完成它。 我认为英语不是 Eddwin 的第一语言,我们必须合理对吧?
  • 定义合理。对于 StackOverflow,我将其定义为回答精心设计的问题。不应鼓励此类家庭作业问题以及格式错误的问题(无论原因如何)。
  • 我是 SO 上最具侵略性的“关闭”r :) 这是一个艰难的决定;如果您认为它应该关闭,请单击关闭按钮。对我来说,这只是一个简单的问题,在一个困难的领域,但有许多语法错误/类似的错误(比如提到“Xcode”)。修辞问题并没有真正的帮助,只会增加混乱。尽量不要(像我一样)粗鲁:)
  • 我自己解决了这个问题,这很简单,我只需要正确定位字典并将 indexpath.row 添加到 tableView。注:感谢有善意的人,也感谢谦虚的人的帮助。英语是我的第二语言,我是 xcode 的新手,所以无法提出一个好的问题。只是想让下面那些表现得很粗鲁的人。 “在跑步之前,我们必须学会走路”
  • Epa 埃德温!你知道,最近在这个网站上有一个“危机”的蹩脚问题你知道吗?有趣的是,有时我会问一些关于一些晦涩难懂的问题。每个人都认为这是一个可怕的问题并试图关闭它:)(你可以看到很多这样的例子,stackoverflow.com/questions/22896298/…)就像 Leo 所说,人们会问“家庭作业”问题,你知道吗?版主试图整理网站。我认为有时像你这样有好问题的人会被“抓住”!呵!我希望这是有道理的。超!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多