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

时间:2013-10-13 22:15:10

标签: 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

谢谢!

3 个答案:

答案 0 :(得分:1)

// 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
        }
    });    
});

答案 1 :(得分:0)

  1. 请查看此链接Understanding dispatch_async和此https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html
  2. 您应该添加DISPATCH_QUEUE_PRIORITY_BACKGROUND而不是DISPATCH_QUEUE_PRIORITY_DEFAULT来在后台运行此功能。
  3. 通过使用DISPATCH_QUEUE_PRIORITY_DEFAULT,您只需将任务归类为正常任务。如果您已将其更改为更高或更低的优先级,则队列将分别在其他任务之前或之后运行它。

答案 2 :(得分:0)

你应该这样做:

self.model = arr;

self的引用会调用setter,它将释放该变量中的所有先前引用,然后将引用计数添加到arr,这样它就不会超出范围。如果你直接访问ivar,你会这样做:

[model release];
model = [arr retain];