1

我有一个从数组中获取数据的 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

谢谢!

4

3 回答 3

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
        }
    });    
});
于 2013-10-14T08:08:45.820 回答
0
  1. 看看这个链接了解 dispatch_async和这个https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html
  2. 您应该添加DISPATCH_QUEUE_PRIORITY_BACKGROUND而不是DISPATCH_QUEUE_PRIORITY_DEFAULT在后台运行它。

通过使用DISPATCH_QUEUE_PRIORITY_DEFAULT您刚刚使您的任务被归类为正常任务。如果您将其更改为更高或更低的优先级,则队列将分别在其他一些任务之前或之后运行它。

于 2013-10-13T22:23:15.357 回答
0

你应该做:

self.model = arr;

引用self调用设置器,它将释放该变量中的任何先前引用,然后添加一个引用计数,arr这样它就不会超出范围。如果您直接访问 ivar,您将执行以下操作:

[model release];
model = [arr retain];
于 2013-10-13T22:27:40.820 回答