【发布时间】:2016-07-16 23:50:15
【问题描述】:
我已经能够从本地 JSON 文件中获取数据以显示在 tableview 中
但它的显示如下:
........ 单元格 1........ ........
饼干
3 杯通用面粉
2 汤匙泡打粉
1/2 茶匙盐
........ 单元格 2....................... ........
12 个完整的晚餐卷或小三明治面包(我用的是全麦)
1 磅削薄的烤牛肉或火腿(或两者兼有!)
.................................................. .......
而且我需要它来显示分离到自己的单元格中的每种成分,如下所示:
........ 单元格 1........ ........
饼干
........ 单元格 2....................... ........
3 杯通用面粉
........ 单元格 3....................... ........
2 汤匙泡打粉
........ 单元格 4....................... ........
1/2 茶匙盐
........ 单元格 5........ ........
12 个完整的晚餐卷或小三明治面包(我用的是全麦)
....................... 单元格 6....................... ........
1 磅削薄的烤牛肉或火腿(或两者兼有!)
.................................................. …………
我需要什么代码才能正确显示数据?这是我当前的代码:
/////////locations.json/////////////////////////////
{
"locations": [
{ "ingredients" : "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\nShortened for example” },
{ "ingredients" : "12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)\n1 pound Thinly Shaved Roast Beef Or Ham (or Both!)\nShortened for example” },
//many more records. only included 2 for example
]
}
/////////Location.h/////////////////////////////////////////
#import <Foundation/Foundation.h>
@interface Location : NSObject
- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary;
@property (readonly) NSString *ingredients;
@end
////////Location.m////////////////////////////////////
#import "Location.h"
@implementation Location
// Init the object with information from a dictionary
- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary {
if(self = [self init]) {
// Assign all properties with keyed values from the dictionary
_ingredients = [jsonDictionary objectForKey:@"ingredients"];
}
return self;
}
@end
////////JSONLoader.h////////////////////////////////////
#import <Foundation/Foundation.h>
@interface JSONLoader : NSObject
// Return an array of Location objects from the json file at location given by url
- (NSArray *)locationsFromJSONFile:(NSURL *)url;
@end
////////JSONLoader.m////////////////////////////////////
#import "JSONLoader.h"
#import "Location.h"
@implementation JSONLoader
- (NSArray *)locationsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
// Get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Create a new array to hold the locations
NSMutableArray *locations = [[NSMutableArray alloc] init];
// Get an array of dictionaries with the key "locations"
NSArray *array = [jsonDictionary objectForKey:@"locations"];
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
// Create a new Location object for each one and initialize it with information in the dictionary
Location *location = [[Location alloc] initWithJSONDictionary:dict];
// Add the Location object to the array
[locations addObject:location];
}
// Return the array of Location objects
return locations;
}
@end
////////TableViewController.h////////////////////////////////////
#import <UIKit/UIKit.h>
#import "Location.h"
@interface FilterViewController : UITableViewController
@property (weak, nonatomic) Location *location;
@end
////////TableViewController.m////////////////////////////////////
#import "FilterViewController.h"
#import "LocationsViewController.h"
#import "Location.h"
#import "JSONLoader.h"
@implementation FilterViewController {
NSArray *_locations;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Create a new JSONLoader with a local file URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"json"];
// Load the data on a background queue...
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_locations = [jsonLoader locationsFromJSONFile:url];
// Now that we have the data, reload the table data on the main UI thread
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
// Just before showing the LocationDetailViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
LocationsViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.location = [_locations objectAtIndex:indexPath.row];
}
#pragma mark - Table View Controller Methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FilterCell"];
Location *location = [_locations objectAtIndex:indexPath.row];
cell.textLabel.text = location.ingredients;
cell.imageView.image = [UIImage imageNamed:@"ingredientsicon3232.png"];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_locations count];
}
@end
注意:我无法更改 JSON 数据格式,因为它来自外部来源,并且“成分”键比我在示例中发布的要多得多。
【问题讨论】:
-
我从你的代码中得到的是你使用了错误的数组来表示节数。如果您使用“位置”数组对象设置 cell.textlabel.text,那么也将其用于您的部分数量。然后将section中的行数设置为1。
-
@roozbehmo 感谢您分享您的建议。你能在代码中提供这个建议吗?我没有看到我的代码中的部分数量并试图理解。对此仍然很陌生,并正在努力学习。谢谢!
标签: ios objective-c arrays json uitableview