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

問題を正しく理解している場合、ブロック内で変数を宣言し、それを外部で使用しようとしています。

それはうまくいきません。ブロック内で宣言された変数は、ブロックのスコープに限定されます。ブロック内でそれらを作成すると、ブロック内での使用に制限され、他の場所では使用できなくなります。

より良いアイデアは、ブロックの外で使用したい変数を作成することです。ブロック内の変数を変更する場合は、__block キーワードを使用します。

__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

ブロック内で定義されている変数は、そのブロックに対してローカルであるため、ブロックの外には存在しません。ブロックに入る前にこれらの変数を事前に定義することができますが、これは特殊な領域に入り、これらの変数を定義するときに拡張機能を使用する必要があります。オーガナイザーで「__block」ストレージ タイプを検索します。詳細を考慮して、これが適切なアドバイスであるかどうかを判断するために、コードのレビューにあまり時間をかけませんでした。

于 2012-08-08T18:34:50.997 に答える