I have this code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
point =[touch locationInView:imageView];
[self openImages];
}
evrytime I touch screen it call "openImages" method;
- (void) openImages{
// some code....
for(int i = 0; i < 200; i++){
for(int j = 0; j < 200; j++){
//some code...
}
}
}
then you can see that "openImage" is a heavy method because there is a double loop where i open some uiimage (but it's not the problem). My question is that: what I can do to stop openImages everytime I touch screen, and call it one more time (because if i often touch screen app crash). Can you help me?
You can use NSOperationQueue
for this. Make openImages
into operation which can be cancelled. On each touch you can get all "open image" operations from queue, cancel them and enqueue new operation.
To elaborate:
Make an instance variable for your queue and initialize it before doing anything:
imageOperationsQueue = [NSOperationQueue new];
Operation can be implemented like this:
@interface OpenImagesOperation : NSOperation
@end
@implementation OpenImagesOperation
- (void)main {
for (int i = 0; !self.isCancelled && i < 200; i++) {
for (int j = 0; !self.isCancelled && j < 200; j++) {
//some code...
}
}
}
@end
openImages
method now looks like
- (void)openImages {
for (NSOperation *o in imageOperationsQueue.operations) {
if ([o isKindOfClass:[OpenImagesOperation class]]) {
[o cancel];
}
}
[imageOperationsQueue addOperation:[OpenImagesOperation new]];
}