为了测试我的应用的JSON
处理,我创建了一个test.json文件,我想将其加载到UITableView
类的UIViewController
中。我创建了JSON
文件并创建了一个单独的json加载类(JSONLoader
)来实现代码:
#import <Foundation/Foundation.h>
@interface JSONLoader : NSObject
//return an array of chat objects from the json file given by url
- (NSArray *)chattersFromJSONFile:(NSURL *)url;
@end
在 .h 文件中,在 .m 文件中我有:
#import "JSONLoader.h"
#import "Chatter.h"
@implementation JSONLoader
- (NSArray *)chattersFromJSONFile:(NSURL *)url {
//create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
//get data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//create NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//create new array to hold chatter information
NSMutableArray *localChatters = [[NSMutableArray alloc] init];
//get an Array of dictionaries with the key "chatters"
NSArray *chatterArray = [jsonDictionary objectForKey:@"chatters"];
//iterate through array of dictionaries
for(NSDictionary *dict in chatterArray) {
//create new chatter object for each one and initialize it with info from the dictionary
Chatter *chatter = [[Chatter alloc] initWithJSONDictionary:dict];
//add the chatter to an array
[localChatters addObject:chatter];
}
//return array
return localChatters;
}
@end
我认为哪个版本适用于从JSON
(最终目标)加载的URL
文件以及我在 Xcode JSON文件>项目作为测试。在我的 viewController.m 文件的-viewDidLoad
中,我使用:
//create a new JSONLoader with a local file from URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"json"];
NSLog(@"%@",url);
//load the data on a background queue
//use for when connecting a real URL
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_localChatters = [jsonLoader chattersFromJSONFile:url];
NSLog(@"%@",_localChatters);
//push data on main thread (reload table view once JSON has arrived)
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
});
我导入JSONLoader
文件以及代表测试JSON
对象的类(单数聊天),在我的实现中我声明了NSArray *_localChatters
。
我非常确信这应该有效,但是当我NSLog(...)
数组时它显示为空()
,它应该有一个类对象列表。这意味着JSON
永远不会被我的JSONLoader
解析。
这可能发生的任何特殊原因?