detachNewThreadSelector crashes the app randomly - iphone

I am developing an iphone app in which I am extracting RSS feeds and then parsing them.My code is as bellow:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(#"in view did appear");
if ([stories count] == 0) {
NSString * path = #"http://www.shire.com/shireplc/rss.jsp";
//[self parseXMLFileAtURL:path];
//[self performSelectorInBackground:#selector(parseXMLFileAtURL:) withObject:path];
NSLog(#"internet is %d",[self checkInternet]);
if([self checkInternet]==1)
[NSThread detachNewThreadSelector:#selector(parseXMLFileAtURL:)
toTarget:self withObject:path];
}
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
stories = [[NSMutableArray alloc] init];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
[pool release];
}
Can anyone tell me where I am going wrong?
My log is as bellow:
log: [Switching to thread 12803]
[Switching to thread 12035]
2011-05-10 11:31:30.932 Annual Report[454:490b] found file and started parsing
[Switching to thread 14339]
2011-05-10 11:32:04.742 Annual Report[454:640b] found file and started parsing
[Switching to thread 13827]
[Switching to thread 13827]
Program received signal: “EXC_BAD_ACCESS”.
gdb stack trace at 'putpkt: write failed':
0 gdb-arm-apple-darwin 0x0019026b remote_backtrace_self + 54

I am not sure but i guess the parameter for the method gets released at some point. Can you make sure that the URL is present in the method parseXMLFileAtURL

Finally,I used a flag to check if the view is appeared or not(by making flag true in viewdidAppear) and if the view is not appearing,don't run the thread function.That solved the problem!!!

// you can use the method, which is safer if your have not to update the UserInterface
[self performSelectorInBackground:#selector(parseXMLFileAtURL:) withObject:path];
if UserInterface needs also to be updated you can first parse data in background and the update the ui with method.
[self performSelectorOnMainThread:#selector(myUpdateUI) withObject:nil waitUntilDone:YES];

Related

NSThread is blocking my GUI

I use a NSThread in order to download videos and images from a server side.It work looks and works great except the fact that when the downloading is done my GUI gets blocked until the download is complete.When the download is finished it takes a few seconds to work again.
this is how the server request is done:
- (void) repeatRequest{
NSLog(#"repeatRequest");
[NSThread detachNewThreadSelector:#selector(backgroundRequest) toTarget:self withObject:nil];
}
- (void) backgroundRequest{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:myURLStr];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
[pool drain];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
//do things
}
IMPORTANTAnd I also tried to start the ASIHTTPRequest from the GUI thread but with the same behaviour.
Any idea about what could be wrong?
EDIT:
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
//internetReachable = [[Reachability reachabilityForInternetConnection] retain];
if(timer1 == nil)
{
timer1 = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector: #selector(repeatRequest) userInfo: nil repeats: YES];
}
}
Try to run synchronous ASIHTTPRequest in your background thread, and handle results not in delegate method (requestFinished), but after [request startSynchronous];
I don't know anything about ASIHTTPRequest but i would assume its -startAsynchronous method already handles the background downloading for you. It all likelihood, it is returning immediately and your new thread is exiting. Also, you should just use [pool release] at the end of a thread method instead of [pool drain], it will be drained upon release, and you won't be leaking an NSAutoReleasePool. Does ASIHTTPRequest have a -startSynchronous (or just plain -start) method? Try using that within -backgroundRequest, as it should block the premature exit of that thread.

Memory allocation in detached NSThread to load an NSDictionary in background?

I am trying to launch a background thread to retrieve XML data from a web service. I developed it synchronously - without threads, so I know that part works. Now I am ready to have a non-blocking service by spawning a thread to wait for the response and parse.
I created an NSAutoreleasePool inside the thread and release it at the end of the parsing. The code to spawn and the thread are as follows:
Spawn from main-loop code:
.
.
[NSThread detachNewThreadSelector:#selector(spawnRequestThread:)
toTarget:self withObject:url];
.
.
Thread (inside 'self'):
-(void) spawnRequestThread: (NSURL*) url {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[self parseContentsOfResponse];
[parser release];
[pool release];
}
The method parseContentsOfResponse fills an NSMutableDictionary with the parsed document contents. I would like to avoid moving the data around a lot and allocate it back in the main-loop that spawned the thread rather than making a copy. First, is that possible, and if not, can I simply pass in an allocated pointer from the main thread and allocate with 'dictionaryWithDictionary' method? That just seems so inefficient.
parseContentsOfResponse
-(void)parseContentsOfResponse {
[parser setDelegate:self];
[parser setShouldProcessNamespaces:YES];
[parser setShouldReportNamespacePrefixes:YES];
[parser parse];
NSError *parseError = [parser parserError];
if (parseError) {
NSLog(#"%#", parseError);
NSLog(#"publicID: %#", [parser publicID]);
NSLog(#"systemID: %#", [parser systemID]);
NSLog(#"line:%d column:%d", [parser lineNumber], [parser columnNumber]);
}
ready = YES;
}
First parse section
Each section creates element strings when its elementStart is signaled. The elementEnd will add the object to the dictionary and release the element. The remaining details are redundant and I think the point to note is that the allocations are not directed at an NSZone, therefore they should be residing in the thread's memory pool.
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(#"%s", __FUNCTION__);
currentChars = [NSMutableString stringWithString:#""];
elementQuestion = [NSMutableString stringWithString:#""];
elementAnswer = [NSMutableString stringWithString:#""];
elementKeyword = [NSMutableString stringWithString:#""];
}
The simplest thing to do would be to create the dictionary in the separate thread, then set it as a property on the main thread, like so:
- (void)spawnRequestThread: (NSURL*) url {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//do stuff with dict
[self performSelectorOnMainThread:#selector(doneWithThread:) withObject:dict waitUntilDone:NO];
}
- (void)doneWithThread:(NSDictionary *)theDict {
self.dict = theDict; //retaining property, can be an NSDictionary
}
Do you need to change the contents of the dictionary over time? If so, allocating on the main thread and changing the contents in the other thread is possible, but you have to worry about thread-safety issues--NSMutableDictionary isn't thread-safe, so you'd have to use an atomic property and locks:
//.h
#property (retain) NSMutableDictionary *dict; //don't use "nonatomic" keyword
#property (retain) NSLock *dictLock;
//.m
- (id) init {
//blah blah
dict = [[NSMutableDictionary alloc] init];
dictLock = [[NSLock alloc] init];
return self;
}
- (void)spawnRequestThread: (NSURL*) url {
//whenever you have to update the dictionary
[self.dictLock lock];
[self.dict setValue:foo forKey:bar];
[self.dictLock unlock];
}
Locking is quite expensive and inefficient in any case, so I'd tend to prefer the first method (I'm not sure which is more expensive, exactly, but the first is simpler and avoids thread-safety issues).
Also, looking at your code, it looks like your NSXMLParser is an ivar which you directly access. This is a bad idea, since NSXMLParser isn't thread-safe--I would recommend implementing it as a local variable instead. If you do need it as an ivar, use an atomic property and locks and only access it through accessors.

Stop NSXMLParser Instance from Causing _NSAutoreleaseNoPool

In my iPhone application, I have an instance of NSXMLParser that is set to a custom delegate to read the XML. This is then moved into its own thread so it can update the data in the background. However, ever since I have done this, it has been giving me a lot of _NSAutoreleaseNoPool warnings in the console. I have tried to add a NSAutoreleasePool to each of my delegate classes, however, this hasn't seemed to solve the problem. I have included my method of creating the NSXMLParser in case that is at fault.
NSURL *url = [[NSURL alloc] initWithString:#"http://www.mywebsite.com/xmlsource.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
CustomXMLParser *parser = [[CustomXMLParser alloc] init];
parser.managedObjectContext = self.managedObjectContext;
parser = [parser initXMLParser];
[xmlParser setDelegate:parser];
[NSThread detachNewThreadSelector:#selector(parse) toTarget:xmlParser withObject:nil];
If anyone has any ideas to get rid of this problem, I would really appreciate it.
Thanks.
In objective-c each thread needs its own NSAutorelease pool to handle autoreleased objects. So in your parse method you need to create (and release) NSAutoreleasePool object:
- (void)parse{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
...
// your method implementation
...
[pool release];
}

iPhone: Parsing multiple XML with NSXMLParser in background disturbing each other

I have a strange issue, when it comes to parsing XML with NSXMLParser on the iPhone. When starting the app, I want to preload 4 table-views, that are populated by RSS-Feeds in the background.
When I init the table-views one-by-one, than loading, parsing and displaying all works like a charm. But when I try to init all view at once (at the same time), than it seems, that the XML-parser-instances are disturbing each other. Somehow data from one XML-Feed are "broadcasted" into other xml-parser instances, where they do not belong. Example: there is a "teammember" item, with "This is my name". When this bug occurs, there is a string from another xml-feed added, i.e. resulting in: "This is my name58", where 58 is the chart-position of something from the other view. "58" seems to miss then on the other instance.
It looks to me, that this bug occurs because of the NSXMLParser-delegate method:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (!currentStringValue) {
currentStringValue = [[NSMutableString alloc] initWithCapacity:50];
}
[currentStringValue appendString:string];
}
In this case "by coincidence" bytes are appended to strings, where they do not belong to.
The strange thing is, that every instance of NSXMLParser is unique, got its own unique delegates, that are attached to their own ViewController. Every parsing-requests spawns it own background-task, with its own (also also unique named) Autorelease-pool.
I am calling the NSXMLParser like this in the ViewController:
// prepare XML saving and parsing
currentStringValue = [[[NSMutableString alloc] initWithCapacity:50] retain];
charts = [[NSMutableArray alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://(SOME XML URL)"];
xmlParser = [[[NSXMLParser alloc] initWithContentsOfURL:url] retain];
//Set delegate
[xmlParser setDelegate:self];
//loading indicator
progressWheel = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(150.0,170.0,20.0,20.0)] autorelease];
progressWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self.view addSubview:progressWheel];
[progressWheel startAnimating];
// start loading and parsing the xml-feed in the background
//[self performSelectorInBackground:#selector(parse:) withObject:xmlParser]; -> I also tried this
[NSThread detachNewThreadSelector:#selector(parse:) toTarget:self withObject:xmlParser];
And this is one of the background-tasks, parsing the feed:
-(void)parse:(NSXMLParser*)myParser {
NSAutoreleasePool *schedulePool = [[NSAutoreleasePool alloc] init];
BOOL success = [myParser parse];
if(success) {
NSLog(#"No Errors. xmlParser got: %#", myParser);
(POST-PROCESSING DETAILS OF THE DATA RETURNED)
[self.tableView reloadData];
} else {
NSLog(#"Couldn't initalize XMLparser");
}
[progressWheel stopAnimating];
[schedulePool drain];
[myParser release];
}
What could cause this issue? Am I calling the background-task in the right way? Why is this bug approaching, since every XML-Parser got its own, unique instance?
You should not be updating UI elements (like progressWheel) from inside a background thread. UI updates should be done on the main thread.
Use -performSelectorOnMainThread:withObject:waitUntilDone: to update UI elements from within a background thread.
I've released an open source RSS/Atom Parser for iPhone and it makes reading and parsing web feeds extremely easy.
You can set it to download the data asynchronously, or you could run it in a background thread synchronously to collect the feed data.
Hope this helps!

NSXMLParser avoids UILabel to show/hide

I have the following methods in my class:
-(IBAction)loginToAccount:(id)sender {
// Display the network activity status indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Show the load indicator
[self.loadIndicator startAnimating];
self.loadIndicator.hidden = NO;
self.loadLabel.hidden = NO;
[usernameTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
[self CheckLoginCredentials];
}
-(void)CheckLoginCredentials {
NSString *APIURL = [[NSString alloc] initWithFormat:#"http://mysite.com/xml.xml"];
NSURL *url = [[NSURL alloc] initWithString:APIURL];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[APIURL release];
[url release];
[xmlParser setDelegate:self];
[xmlParser parse];
}
When I comment [self CheckLoginCredentials], the loadIndicator gets animated and shown but when I uncomment [self CheckLoginCredentials], the loadIndicator does not get shown and also usernameTextField/passwordTextField resignFirstResponder do no work.
What am I doing wrong? Thanks!
I believe that -initWithContentsOfURL: is a synchronous url connection, and therefore blocks the thread it's run on until it completes.
Because of this, the progress indicator won't get shown because it requires that the thread it's running on has an active run loop. Using the synchronous url connection on the main thread will block the UI on that thread, so you won't see your progress indicator.
The correct way to do this would be to use NSURLConnection's
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate
Simply create an NSURLRequest object that encapsulates your API request, and then pass it off to that method on NSURLConnection.
Then implement the delegate call backs to get your data back.
The advantage of this method is that all of this is done on a separate thread and handled for you, and therefore won't block your UI.