我试图在 viewController 内将 json 解析为我的 tableview。但是当我尝试记录它时,它不会出现。我还想知道如何将此 JSON 放入我的 tableviewcells 中。
自从我第一次提出这个问题以来,我改变了我的代码。
请在下面查看我的代码:
米:
#import "UbaGuideStartViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface UbaGuideStartViewController (){
NSMutableData *jsonData;
NSURLConnection *connection;
NSMutableArray *arrData;
}
@property (weak, nonatomic) IBOutlet UIImageView *ImgHeader;
@property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
@end
@implementation UbaGuideStartViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[[self StartTableView]setDelegate:self];
[[self StartTableView]setDataSource:self];
arrData = [[NSMutableArray alloc]init];
}
//Json parse.
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[jsonData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[jsonData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Failed with error");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *guideDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSArray *arrguideTitle = [guideDictionary objectForKey:@"guide"];
for (NSDictionary *dictionary in arrguideTitle)
{
NSString *guideTitle = [dictionary objectForKey: @"guideTitle"];
[arrData addObject:guideTitle];
}
[self.StartTableView reloadData];
NSURL *url = [NSURL URLWithString:@"http://www.sofisto.com.br/public_html/TEST/guide.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection){
jsonData = [[NSMutableArray alloc]init];
}
}
//TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *startGuideCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (startGuideCell == nil) {
startGuideCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// configure your cell here...
startGuideCell.textLabel.text = [arrData objectAtIndex:indexPath.row];
return startGuideCell;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
还有我的JSON:
{
"guide": [
{ "guideTitle":"Where to stay"},
{ "guideTitle":"Where to eat"},
{ "guideTitle":"What to do"}
]
}
提前致谢!