线程我的项目,但使用队列和块,但是当我尝试对代码进行排队时出现错误。我知道你不能在块中排队 UI 元素,所以我避免了这种情况,但我得到的错误是当我在块外调用 UI 元素时,它说虽然变量在块内声明但未声明变量。这是代码。该代码是一个 UITableView 方法,它只需要一个数组对其进行排序并显示它。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Create an instance of the cell
UITableViewCell *cell;
cell = [self.tableView dequeueReusableCellWithIdentifier:@"Photo Description"];
if(!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Photo Description"];
// set properties on the cell to prepare if for displaying
//top places returns an array of NSDictionairy objects, must get object at index and then object for key
//Lets queue this
dispatch_queue_t downloadQueue = dispatch_queue_create("FlickerPhotoQueue", NULL);
dispatch_async(downloadQueue, ^{
//lets sort the array
NSArray* unsortedArray = [[NSArray alloc] initWithArray:[[self.brain class] topPlaces]] ;
//This will sort the array
NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"_content" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:descriptor];
NSArray *sortedArray = [[NSArray alloc] init];
sortedArray = [unsortedArray sortedArrayUsingDescriptors:sortDescriptors];
NSString * cellTitle = [[sortedArray objectAtIndex:self.location] objectForKey:@"_content"];
NSRange cellRange = [cellTitle rangeOfString:@","];
NSString * cellMainTitle = [cellTitle substringToIndex:cellRange.location];
});
dispatch_release(downloadQueue);
//Claims that this are not declared since they are declared in the block
cell.textLabel.text = cellMainTitle;
//This isnt declared either
NSString* cellSubtitle = [cellTitle substringFromIndex:cellRange.location +2];
cell.detailTextLabel.text = cellSubtitle;
self.location++;
return cell;
}
我设法通过将调度发布移动到代码块的最后,然后通过调用 dispatch_get_main_queue 在主线程中声明 UI 接口来使程序工作。感谢所有的帮助