0

线程我的项目,但使用队列和块,但是当我尝试对代码进行排队时出现错误。我知道你不能在块中排队 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 接口来使程序工作。感谢所有的帮助

4

2 回答 2

6

If I am understanding your problem correctly, you are declaring a variable inside a block and trying to use it outside.

That won't work. Variables declared inside blocks are limited to the block's scope. If you create them inside the block, you are limited to using them in the block and you can't use them anywhere else.

A better idea will be to create the variable you want to use outside the block. If you want to modify the variable in the block, use the __block keyword.

__block UITableViewCell *someCell;
//__block tells the variable that it can be modified inside blocks.
//Some generic block
^{
//initialize the cell here.
}
于 2012-08-08T18:30:45.337 回答
1

在块内定义的变量是该块的本地变量,因此不存在于它之外。您可以在进入块之前预先定义这些变量,但是这是进入一个专门的领域,并且在定义这些变量时需要使用扩展。在 Organizer 中查找“__block”存储类型。我没有花太多时间审查您的代码,以了解这是否是考虑到细节的明智建议。

于 2012-08-08T18:34:50.997 回答