I have a long running loop I want to run in the background with an NSOperation. I’d like to use a block:
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
while(/* not canceled*/){
//do something...
}
}];
The question is, how to I check to see if it’s canceled. The block doesn’t take any arguments, and operation is nil at the time it’s captured by the block. Is there no way to cancel block operations?
Doh. Dear future googlers: of course
operationis nil when copied by the block, but it doesn’t have to be copied. It can be qualified with__blocklike so:UPDATE:
Upon further meditation, it occurs to me that this will create a retain cycle under ARC. In ARC, I believe
__blockstorage is retained. If so, we’re in trouble, becauseNSBlockOperationalso keeps a strong references to the passed in block, which now has a strong reference to the operation, which has a strong reference to the passed in block, which…It’s a little less elegant, but using an explicit weak reference should break the cycle:
Anyone that has ideas for a more elegant solution, please comment!