在块中声明变量,目标C.

Ter*_*son 0 variables queue xcode block objective-c

线程我的项目,但使用队列和块,但我尝试排队代码时收到错误.我知道你不能在块中排列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;
}
Run Code Online (Sandbox Code Playgroud)

我设法通过将调度版本移动到代码块的最后来使程序工作,然后通过调用dispatch_get_main_queue在主线程中声明UI接口.谢谢你的帮助

And*_*nez 6

如果我正确理解您的问题,您将在块内声明一个变量并尝试在外部使用它.

那不行.块内声明的变量仅限于块的范围.如果您在块内创建它们,则只能在块中使用它们,并且您无法在其他任何位置使用它们.

更好的想法是创建要在块外使用的变量.如果要修改块中的变量,请使用__block关键字.

__block UITableViewCell *someCell;
//__block tells the variable that it can be modified inside blocks.
//Some generic block
^{
//initialize the cell here.
}
Run Code Online (Sandbox Code Playgroud)