0

我想要做的是创建一个类,它在调用时返回 Json Data 的 NSDictionary。我过去对图像做过同样的事情,但是我对如何用 NSDictionary 实现它有点困惑。

我想要做的是加载一个视图,然后在后台发送请求以获取一些 Json 数据(异步)并返回包含要使用的数据的字典。我将在很多不同的视图中加载大量 Json 数据,所以它应该是一个可重用的类。

- (id)initWithURL:(NSURL *)url
{
    self = [self init];

    if (self)
    {
        receivedData = [[NSMutableData alloc] init];
        [self loadWithURL:url];
    }

    return self;
}

- (void)loadWithURL:(NSURL *)url    
{
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url]delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSError *error = nil;

    jsonReturn = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

}

我想只是将结果添加到视图可以访问的协议中,但是必须有一种更简单/更清洁的方式对吗?有没有办法让它像这样返回 NSdictionary:

NSDictionary *dictionary = [LoadURLJSon initWithURL:myurl];

它取回了 NSDictionary?

4

2 回答 2

0

您想要的是在异步 API(特别是 )之上的同步操作[NSURLConnection start]。如果没有一些繁重的线程杂耍,你就无法做到这一点,无论如何这都是个坏主意 - 异步确实是要走的路。不要抛弃异步性。

执行一次性异步检索方法的最佳方法是构建一个以 URL、一个NSObject和一个选择器作为参数的方法,一旦请求完成,就在所述对象上调用所述选择器,并提供 NSDictionary 作为参数. 这就是 Objective C 的回调方式。

该方法将在内部实例化您的类,传递回调信息,并启动请求。完成请求并将 JSON 解析为 NSDictionary 后,您将调用[performSelector:]callback NSObject

如果您毕竟想要同步操作,请使用[NSURLConnection sendSynchronousRequest]而不是[NSURLConnection start].

于 2012-06-16T02:09:30.643 回答
0

这就是我的结局!应该对以后路过这里的人有用。

 #import <Foundation/Foundation.h>

@protocol LoadJsonDelegate <NSObject, NSURLConnectionDelegate>
@optional
- (void) downloadFinished;
- (void) downloadReceivedData;
- (void) dataDownloadFailed: (NSString *) reason;
@end

@interface LoadURLJson : NSObject
{
    NSMutableData *receivedData;
    int expectedLength;
}

@property (nonatomic, strong) NSMutableData *receivedData;
@property (strong) NSString *urlString;
@property (weak) id <LoadJsonDelegate> delegate;

-(void)start;
-(void)cancel;

+ (id)download:(NSString *)aURLString withDelegate:(id <LoadJsonDelegate>)aDelegate;

@end

他们

#import "LoadURLJson.h"
#define SAFE_PERFORM_WITH_ARG(THE_OBJECT, THE_SELECTOR, THE_ARG) (([THE_OBJECT respondsToSelector:THE_SELECTOR]) ? [THE_OBJECT performSelector:THE_SELECTOR withObject:THE_ARG] : nil)

@implementation LoadURLJson

@synthesize receivedData, delegate, urlString;

+ (id) download:(NSString *)aURLString withDelegate:(id <LoadJsonDelegate>)aDelegate
{
    if (!aURLString)
    {
        NSLog(@"Error. No URL string");
        return nil;
    }

    LoadURLJson *loadJson = [[self alloc] init];
    loadJson.urlString = aURLString;
    loadJson.delegate = aDelegate;
    [loadJson start];

    return loadJson;
}

-(void)start   
{
    receivedData = [NSMutableData data];
    NSURL *url = [NSURL URLWithString:urlString];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url]delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];

    // Check for bad connection
    expectedLength = [response expectedContentLength];
    if (expectedLength == NSURLResponseUnknownLength)
    {
        NSString *reason = [NSString stringWithFormat:@"Invalid URL [%@]", urlString];
        SAFE_PERFORM_WITH_ARG(delegate, @selector(dataDownloadFailed:), reason);
        [connection cancel];
        [self cleanup];
        return;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    SAFE_PERFORM_WITH_ARG(delegate, @selector(downloadReceivedData), nil);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    SAFE_PERFORM_WITH_ARG(delegate, @selector(downloadFinished), nil);
}

-(void)cleanup
{
    self.urlString = nil;
}

-(void)dealloc
{
    [self cleanup];
}

-(void)cancel
{
    [self cleanup];
}

@end

用法 - 在 yourView.h

#import "LoadURLJson.h"

@interface ViewController : UIViewController <LoadJsonDelegate>
{
    LoadURLJson *loadJson;
}

优视.m

致电:

loadJson = [LoadURLJson download:@"url" withDelegate:self];

然后实施

-(void)downloadFinished
{
    NSData *data = [[NSData alloc] initWithData:loadJson.receivedData];

    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:&error];

    NSLog(@"%@",dictionary);
}

基于此处的 DownloadHelper:https ://github.com/erica/iOS-5-Cookbook

BSD 许可证。

于 2012-06-16T06:14:11.987 回答