ios - 在后台线程中下载和解析数据

标签 ios objective-c

我有一个从数组中获取数据的 UITableView。然而,填充该数组需要从 Web 下载和解析大量数据。既然如此,我想在后台线程中执行这些操作。这是我到目前为止所得到的:

@interface MyClass()

@property (nonatomic, strong) NSArray *model;

@end


@implementation MyClass

- (void) getData {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:SOME_URL]];
       if (data) {
          NSMutableArray *arr = [NSMutableArray array];
          //Populate arr with data just fetched, which can take a while
          dispatch_async(dispatch_get_main_queue(), ^{
             //THIS IS THE STEP I AM UNSURE ABOUT. SHOULD I DO:
             self.model = arr;
             //OR
             self.model = [NSArray arrayWithArray:arr];
             //OR
             self.model = [arr copy];
             //OR
             //something else?
          });
      }
  });
}

@end

谢谢!

最佳答案

// you can use any string instead "mythread"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

dispatch_async(backgroundQueue, ^{
   // Send Request to server for Data
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:SOME_URL]];

    dispatch_async(dispatch_get_main_queue(), ^{
        // Receive Result here for your request and perform UI Updation Task Here
        if ([data length] > 0) {
           // if you receive any data in Response, Parse it either (XML or JSON) and reload tableview new data
        }
    });    
});

关于ios - 在后台线程中下载和解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19350917/

相关文章:

ios - 取消 iOS 版本

ios - XCode 5 完成了吗?

ios - 使用带数组的 NSDictionary 创建 JSON 文件

objective-c - 无法使用 writeToFile 完成操作

ios - Firebase iOS : Download image for TableView - Best Practice

ios:在 iphone6 上运行时增加 UIViewController 中自定义 View 的宽度

ios - 如何解释 XCode 核心数据中的删除规则?

objective-c - 如何正确使用自定义 View ?

iphone - 将换行符附加到 NSString

ios - 从 UitableView 项目中获取值