views:

494

answers:

1

I am trying to download some XML on another thread, and parse it.

I release the 'controller' then call cancelAllOperations on the NSOperationQueue. And implement method 'cancel' on NSoperation which attempts to set nSXMLParser's delegate to nil.

But a second or so later the NSXMLParser is still alive and kicking and calls methods on it's delegate (which now no longer exists) causing a crash.

I just dont get it, what am I doing wrong?

#import "LoadXMLTheadedController.h"
#import "LoadXMLThreaded.h"


 @implementation LoadXMLTheadedController


- (id)initWithURLString:(NSString *)newString
{self = [super init]; 

queue  = [[NSOperationQueue alloc] init];

loadXMLThreaded = [[LoadXMLThreaded alloc] initWithDelegate:self andXMLURLString:newString];

[queue addOperation:loadXMLThreaded];

return self;
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName     namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@" do some parsing.. ");

}


- (void)dealloc {

[[NSNotificationCenter defaultCenter] removeObserver:self];
[queue cancelAllOperations];

[loadXMLThreaded release];
[queue release];
[super dealloc];
}
@end

//----------------------------------------------------------------//

#import "LoadXMLThreaded.h"

@implementation LoadXMLThreaded



- (id)initWithDelegate:(id)newDelegate andXMLURLString:(NSString *)newString
{
[super init];

delegate = newDelegate;
url = [[NSURL URLWithString:newString]retain];

return self;
}


- (void)cancel{

nSXMLParser.delegate = nil;
[nSXMLParser abortParsing];

 }
- (void)main {


nSXMLParser = [[NSXMLParser alloc]initWithContentsOfURL:url];
nSXMLParser.delegate = delegate;
[nSXMLParser parse]; 
}

 - (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
nSXMLParser.delegate = nil;
[nSXMLParser abortParsing];
[nSXMLParser release];
[url release];
[super dealloc];
}
@end
A: 

Apple's documentation:

abortParsing

Stops the parser object.

- (void)abortParsing

Discussion

If you invoke this method, the delegate, if it implements parser:parseErrorOccurred:, is informed of the cancelled parsing operation.

I'm just guessing. Normally sending a method to nil isn't a problem in Objective-C. But maybe NSXMLParser does something fancy internally.

General remarks about your code

  • Learn how to write the init method correctly.
  • You don't have to set the delegate of an object to nil that is going to be deallocated anyway.
Georg
I am calling abortParsing in the method 'cancel' but it's not canceling, this is the problem.
regarding sending nil to delegate, I merely tried this in hope that it would stop NSXMLParser as abortParsing was failing to kill it.