开发者

NSOperation and reloading the parser

I have a parser class that is subclass of NSOperation. It is used to parse the xml and table view is reloaded when the parse is completed. I have a refresh UIBarButtonItem that is used to call the parser and parse the new xml from the link again.

-(void)refresh {
   [self.queue cancelAllOperations]; //cancel all the current operations
   [self.queue release];
   self.queue=nil;
   self.arrayOfAllPhotos = nil; // The array to load table view
   [self performSelectorOnMainThread:@selector(doItAgain) withObject:nil waitUntilDone:NO];

}

-(void)doItAga开发者_StackOverflow社区in {
   [tableView reloadData];
   NSURL *url = [NSURL URLWithString:@"some url"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLConnection *aconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   self.myConnection = aconnection;
   [aconnection release];   

}

But, as press refresh button, the app crashes with no message. How do I release the NSOperationQueue and start a new parsing again to load data ?


Your memory management is broken. And you are violating encapsulation. You are calling [self.queue release]. That is reaching into self and breaking it by releasing something self owns.

If I were to reach into your abdomen and release your liver, it might be all for the good of the country, but it probably would be bad for you. This concept is known as encapsulation. The concept is explained here.

Violating encapsulation is bad for any number of reasons and it's bad for self here.

Instead just call self.queue = nil and the setQueue: method will release queue for you when it's the right time (just like it does for arrayOfPhotos).

[self.queue cancelAllOperations];
self.queue = nil;
self.arrayOfAllPhotos = nil;

Taking a step back from the particulars of this issue it appears that you could also spend some time getting a deeper understanding of the MVC paradigm. The WWDC 2010 talk (Session Title: Model-View-Controller for iPhone OS) about it was fantastic and can be found here (you have to log in).

Generally it is a bad idea to conflate networking with your table view controller.

Good luck!


if queue is defined as retained property then here:

   [self.queue release];
   self.queue=nil;

you are overreleasing queue: it is first released manually, then in the setter method since queue is still not nil and different than nil it will be again released and set to nil and second release will cause the crash.

this will be enough:

   self.queue=nil;


You should be careful after calling cancelAllOperations, its an asynchoronos operation. The simplest way to ensure all operations have been cancelled it to do something like:

[self.queue cancelAllOperations]
[self.queue waitUntilAllOperationsAreFinished];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜