0

这很可能是一个非常微不足道的问题,但我设置了与 API 的连接以检索信息。现在我已经在 viewDidLoad 中设置了所有内容。我知道有一种更有效的方法可以放置这些信息以供用户以后访问,但是我在 Objective-C 方面的经验太少,不知道该怎么做。这就是我目前的全部布局。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.myurl.com"]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];

    NSString *myString = [[NSString alloc] initWithData:myResponse encoding:NSUTF8StringEncoding];

    SBJsonParser *myParser = [[SBJsonParser alloc] init];

    NSArray *myData = [parser objectWithString:myString error:nil];
4

2 回答 2

1

试试这个:

- (void)loadAndParseURL:(NSString *)URLString
             completion:(void (^)(NSArray *data))completion {

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    dispatch_async(dispatch_get_global_queue(DISPATH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];

      NSString *myString = [[NSString alloc] initWithData:myResponse encoding:NSUTF8StringEncoding];

      SBJsonParser *myParser = [[SBJsonParser alloc] init];

      NSArray *myData = [parser objectWithString:myString error:nil];
      completion(myData);
    });
}

completion是一个块(匿名函数指针),它接受一个数组作为参数并执行自定义代码块。该块保存局部变量的值,也就是“环境”,并在执行时评估其内容(通常有某种延迟),在这个例子中, aftermyData是从myString. dispatch_async将发送请求并执行其他操作的匿名块放入后台队列(当然是在后台线程中)。所以这个方法的调用甚至在收到响应之前就返回了,你应该在completion块内安排任何事情。

于 2013-01-23T16:44:49.957 回答
0

如果您正在寻找将其旋转到线程中的内容,我将使用 sendAsynchronousRequest

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
   NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   SBJsonParser *myParser = [[SBJsonParser alloc] init];

    NSArray *myData = [parser objectWithString:myString error:nil];

   // Do what you want with the response and subscribe 
   //anywhere in your code to get notified when it completed.
   [[NSNotificationCenter defaultCenter] 
          postNotificationName:@"NotifyMeWhenDone" 
                        object:self];

}];
于 2013-01-23T17:29:55.343 回答