How can I disable a button while NSXMLParser runs, then enable it when it completes? - iphone

I have a viewController which imports XMLParser.h as the class xmlParser
I'm passing an NSURL object in my viewController to the xmlParser class with the getXML method below
goButton is the button I tap to call the getXML method below. I disable the button which I tapped to trigger the getXML method, but I'm not sure where to put the code to enable it again once the xmlParser has finished parsing the returned XML.
- (IBAction) getXML {
goButton.enabled = NO;
// allocate and initialize the xmlParser
xmlParser = [[XMLParser alloc] init];
// then generate the URL we are going to pass to it and call the fetchXML method passing the URL.
NSURL *xmlurl = [[NSURL alloc] initWithString:#"http://www.mysite.com/myfile.xml"];
[xmlParser fetchXMLFromURL:xmlurl];
// release objects
[xmlurl release];
[xmlParser release];
}
As per #Squeegy recommendation, I modified my code.
- (IBAction) getXML {
goButton.enabled = NO;
xmlParser = [[XMLParser alloc] init];
[self performSelectorInBackground:#selector(parseInBackground:) withObject:xmlParser];
}
- (void)parseInBackground:(XMLParser*)parser {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *xmlurl = [[NSURL alloc] initWithString:#"http://www.mysite.com/myfile.xml"];
[parser fetchXMLFromURL:xmlurl];
[self performSelectorOnMainThread:#selector(didFinishXMLParsing:) withObject:parser];
[xmlurl release];
[pool drain];
}
- (void)didFinishXMLParsing:(NSXMLParser*)parser {
goButton.enabled = YES;
}
Looks to be working until it gets to the line
[self performSelectorOnMainThread:#selector(didFinishXMLParsing:) withObject:parser];
The compiler complains as follows:
2010-02-17 00:22:20.574 XMLApp[2443:521b] *** -[viewController performSelectorOnMainThread:withObject:]: unrecognized selector sent to instance 0x1285a0
2010-02-17 00:22:20.578 XMLApp[2443:521b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[viewController performSelectorOnMainThread:withObject:]: unrecognized selector sent to instance 0x1285a0'
2010-02-17 00:22:20.583 XMLApp[2443:521b] Stack: (
861696817,
860329709,
861700631,
861203093,
861166272,
18715,
846004025,
845672609,
848189713
)

- (IBAction)getXML {
goButton.enabled = NO;
xmlParser = [[XMLParser alloc] init];
NSURL *xmlurl = [[NSURL alloc] initWithString:#"http://www.mysite.com/myfile.xml"];
[xmlParser fetchXMLFromURL:xmlurl];
[self performSelectorInBackground:#selector(parseInBackground) withObject:xmlParser];
[xmlurl release];
[xmlParser release];
}
- (void)parseInBackground:(NSXMLParser*)parser {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[parser parse];
[self performSelectorOnMainThread:#selector(didFinishXMLParsing:)
withObject:parser
waitUntilDone:NO];
[pool drain];
}
- (void)didFinishXMLParsing:(NSXMLParser*)parser {
goButton.enabled = YES;
}
The trick is to do the processing on a background thread, which allows the UI to do stuff. When parsing is done, you have to make any UI changes back on the main thread.

When the parser finishes parsing, it will call it's delegate's:
- (void)parserDidEndDocument:(NSXMLParser *)parser
In that method, you can re-enable the button. You should probably do so with a performSelectorInMainThread call, since it involves changing a view.

Related

Memory Leak In line of code

My app is working fine, but when I run instrument for checking for leaks, it shows me a leak at this line of code, in purple with a 100.0% mark:
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
Here's the method containing this line:
-(NSString*) languageSelectedStringForKey:(NSString*) key
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"zh" ofType:#"lproj"];
if(selectedLanguage==French)
{
FinalString = [[NSString alloc] initWithFormat:#"http://www.xyz.com/api_com.php?page_id=%d",IDValue];
url = [[NSURL alloc] initWithString:FinalString];
}
else if(selectedLanguage==German)
{
FinalString = [[NSString alloc] initWithFormat:#"http://www.x.com/api_com.php?page_id=%d",IDValue];
url = [[NSURL alloc] initWithString:FinalString];
}
else if(selectedLanguage==Nepali)
{
FinalString = [[NSString alloc] initWithFormat:#"http://www.xy.com/api_com.php?page_id=%d",IDValue];
url = [[NSURL alloc] initWithString:FinalString];
}
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[url release];
//Initialize the delegate.
parser = [[NewsParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
NSString* str=[languageBundle localizedStringForKey:key value:#"" table:nil];
return str;
}
Here's my ViewDidLoad method from which languageSelectedStringForKey is called.
- (void)viewDidLoad
{
// Do any additional setup after loading the view from its nib.
appDelegate = (ProgAppDelegate *)[[UIApplication sharedApplication] delegate];
IDValue = 1;
textLabel.text=[self languageSelectedStringForKey:#"Welcome to Advance Localization"];
[super viewDidLoad];
}
What is causing this leak, and how can I fix it?
this is dealloc method:-
- (void)dealloc
{
[xmlParser release];
[parser release];
[nibLoadedCell release];
[super dealloc];
}
Do you ever call
[xmlParser release];
?
If not, you should release it when you no longer need it. Perhaps in the dealloc method of the same class in which that line appears.
You need to make NewsParser parser an instance variable and release it in the dealloc. Above, you init it, but you don't release it. Of course, you can't because it's a delegate of xmlParser. So, to make sure the object is retained, then properly released, it must be an ivar.
You never release FinalString (at least not in the code you posted)
this is held in the URL, which is held by the parser :)
Also, have you considered what would happen if this function is called twice?
Each time you say
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
you would leak the previous xmlParser ;)
If you are allocating to an instance variable, you have to remember to release the previous object i.e.
[xmlParser release];
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

How to show load bar in ipad app while data is fetching from xml after default png is shown

I am fetching XML data from server i want that when data is loading in progress i show a loading bar with default screen this is code in appDidFinishing
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
RootViewController * rootViewController = [[RootViewController alloc] initWithNibName:#"RootViewController" bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
[self.window addSubview:navigationController.view];
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(55, 67, 100, 100)];
[self.activityIndicator startAnimating];
[self.window addSubview:self.activityIndicator];
[self loadXMlTwo];
[self loadXMlMain];
[self performSelectorInBackground:#selector(loadXMlOne) withObject:nil];
[self.activityIndicator removeFromSuperview];
[window makeKeyAndVisible];
return YES;
}
-(void)loadXMlMain{
NSURL*url= [[NSURL alloc]initWithString:#"http://46.137.28.14/app/ipadApplic/working.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
}
-(void)loadXMlOne{
NSURL*url1=[[NSURL alloc] initWithString:#"http://46.137.28.14/app/ipadApplic/rowone.xml"];
NSXMLParser *xmlParserRow = [[NSXMLParser alloc] initWithContentsOfURL:url1];
//Initialize the delegate.
RowOneParser *parser1 = [[RowOneParser alloc] initXMLParser];
//Set delegate
[xmlParserRow setDelegate:parser1];
BOOL success1 = [xmlParserRow parse];
if(success1)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
}
-(void)loadXMlTwo{
NSURL*urlRowTwo=[[NSURL alloc] initWithString:#"http://46.137.28.14/app/ipadApplic/rowtwo.xml"];
NSXMLParser *xmlParserRowTwo = [[NSXMLParser alloc] initWithContentsOfURL:urlRowTwo];
//Initialize the delegate.
RowTwoParser *parserRowTwo = [[RowTwoParser alloc] initXMLParser];
//Set delegate
[xmlParserRowTwo setDelegate:parserRowTwo];
BOOL successRow = [xmlParserRowTwo parse];
if(successRow)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
}
What you need to do is unblock your main thread while you are doing background fetch of xml data. Easiest way to do that is add your fetch operations in NSOperationQueue. Set up delegates for the class which fetches the xml and handle the response.

iphone-uialertview-thred

in iphone,
i call one webservice For login checking...
When Application Is Underprocess ,, I Show UIAlertview With UIActivityIndicatorView
using thread,,
now i want to enable cancel button ,, means during the process if i want to cancel that process,, then my apps teminates webservice calling
but when i enable cancel button then ERROR OCccur,
Any One Can Help
My COde Is
-(NSMutableString*) getLoginMessage:(NSString*) UserName : (NSString *) Password
{
[NSThread detachNewThreadSelector:#selector(showAlertMethod) toTarget:self withObject:nil];
NSArray *Keys =[[NSArray alloc] initWithObjects:#"LoginName",#"PassWord",nil];
NSArray *KeyValue =[[NSArray alloc] initWithObjects:UserName,Password,nil];
operationName=[[NSString alloc] init];
operationName =#"ClientLogin";
NSString *StrService=[[NSUserDefaults standardUserDefaults] objectForKey:#"WebService"];
NSURL *WebServiceUrl=[WebServiceHelper generateWebServiceHTTPGetURL:StrService : operationName : Keys :KeyValue];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:WebServiceUrl];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser setDelegate:self];
[parser parse];
[Keys release];
[KeyValue release];
[StrService release];
[WebServiceUrl release];
//[parser release];
[NSThread detachNewThreadSelector:#selector(dismissAlertMethod) toTarget:self withObject:nil];
return Result;
}
-(void)showAlertMethod
{
NSAutoreleasePool *pool1=[[NSAutoreleasePool alloc]init];
progressAlert = [[UIAlertView alloc] initWithTitle:#"Loging in...\nPlease wait...\n" message:#"" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
CGRect alertFrame = progressAlert.frame;
UIActivityIndicatorView* activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.frame = CGRectMake(135,alertFrame.size.height+75, alertFrame.size.width,30);
activityIndicator.hidden = NO;
activityIndicator.contentMode = UIViewContentModeCenter;
[activityIndicator startAnimating];
[progressAlert addSubview:activityIndicator];
[activityIndicator release];
[progressAlert show];
[pool1 release];
}
-(void)dismissAlertMethod
{
NSAutoreleasePool *pool2=[[NSAutoreleasePool alloc]init];
[progressAlert dismissWithClickedButtonIndex:0 animated:YES];
[pool2 release];
}
There are some major flaws in how you attack the problem. Firstly you should not detach new threads to show and hide the alert view, all UIKit classes must be called form the main thread (only few documented exceptions exist).
What you want is an API designed to be asynchronous for dispatching the login request. I would suggest you use an Sync-Async pattern for this. I have written a longer blog post on this topic here: http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/
In essence I believe you want two public methods:
-(NSString*)loginMessageWithName:(NSString*)name
password:(NSString*)password
error:(NSError**)error;
-(NSOperation*)loginMessageWithName:(NSString*)name
password:(NSString*)password
delegate:(id<LoginMessageDelegate>)delegate;
The first method is synchronous, implement it as straightforward as you like, no threads on any thing, just make it work.
The second method is a wrapper that instantiates a NSOperation objects and puts it on some queue. Returning the operation allows you to cancel it, but the result will be returned on the delegate. The delegate will probably need to look something like this:
#protocol LogonMessageDelegate <NSObject>
-(void)didReceiveLoginMessage:(NSString*)message;
-(void)failedLoginMessageWithError:(NSError*)error;
#end
The implementation of loginMessageWithName:password:delegate: is very straight forward:
NSOperation* op = [[LoginMessageOperation alloc] initWithName:name
password:password
delegate:delegate];
[myOperationQueue addOperation:op];
return [op autorelease];
Most of the work will be done in your NSOperation subclass' main method. This is where you call the synchronious implementation, check for cancelation, and call back to the delegate if needed. Probably something like this:
-(void)main {
NSError* error = nil;
NSString* message = [logonMessageManager logonWithName:name
password:password:
error:&error];
if (![self isCancelled]) {
if (message) {
[delegate performSelectorOnMainThread:#selector(didReceiveLoginMessage:)
withObject:message
waitUntilDone:NO];
} else {
[delegate performSelectorOnMainThread:#selector(didReceiveLoginMessage:)
withObject:error
waitUntilDone:NO];
}
}
}
Then setup and handle the alert view on the main thread. Call [operation cancel] if the user cancels, or dismiss the alert when the delegate receives a callback.

Asynchronous Loading of Image - Crashing If Dealloced

I have a UIViewController presented by a navigation controller. This UIViewController loads an image asynchronously as follows :
[self performSelectorInBackground:#selector(downloadData) withObject:nil];
- (void)downloadData {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
LocationDetails * details = [[LondonDatabase database] locationDetails : UniqueID];
NSData * imageData = [NSData dataWithContentsOfURL : [NSURL URLWithString : [details image]]];
picture = [[UIImage alloc ]initWithData:imageData];
[self performSelectorOnMainThread : #selector(updateUI) withObject : nil waitUntilDone : NO];
[pool release];
}
The problem is that if this view controller is popped off the stack while the above method is executing the app crashes with the error :
bool _WebTryThreadLock(bool), 0x61b3950: Tried to obtain the web lock
from a thread other than the main thread or the web thread. This may
be a result of calling to UIKit from a secondary thread. Crashing
now...
Can anyone help ?
Thanks,
Martin
Use an NSThread and keep a handle to that in the view controller object. When the view controller dealloc's, cancel the thread (assuming it has not completed). In downloadData, check that the thread isn't cancelled before trying to access elements of the view controller. That is to say, if the thread has been cancelled, just return. I had a similar issue and this is how I solved it.
Here's the code (which was loading an image into a custom table cell):
-(void)displayImage:(id)context
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = (UIImage *)context;
[spinner stopAnimating];
brandImage.image = image;
[brandImage setNeedsDisplay];
[pool release];
}
-(void)fetchImage:(id)context
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *url = (NSString *)context;
if ([[NSThread currentThread] isCancelled])
return;
UIImage *image = [ArtCache imageForURL:url];
if (![[NSThread currentThread] isCancelled]) {
[self performSelectorOnMainThread:#selector(displayImage:) withObject:image waitUntilDone:NO];
}
[pool release];
}
-(void)showBrandImageURL:(NSString *)url
{
[spinner startAnimating];
brandImage.image = nil;
if (imageLoadThread) {
[imageLoadThread cancel];
[imageLoadThread release];
}
imageLoadThread = [[NSThread alloc] initWithTarget:self selector:#selector(fetchImage:) object:url];
[imageLoadThread setThreadPriority:0.8];
[imageLoadThread start];
}
These were 3 methods in the custom table cell class. The last one was the one called from cellForRowAtIndexPath:. The other two support the one that is called.

xml parsing consumes time need efficent way on iphone

How to call main thread ??? i can parse but i cant display data
- (void)viewDidLoad {
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"10.png"]];
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(startTheBackgroundJob) toTarget:self withObject:nil];
}
- (void)startTheBackgroundJob {
NSUserDefaults *getida = [NSUserDefaults standardUserDefaults];
myIDa = [getida stringForKey:#"AppID"];
NSLog(#"#BOOK MARK ");
NSString *ubook = [[NSString alloc] initWithFormat:#"http://www.wapp=%#&action=show",myIDa];
NSLog(#" bookmark %#",ubook);
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//NSString *outputString = [[NSString stringWithString:usearch] stringByAppendingString: UserText];
ubook = [ubook stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"My string is now = %#", ubook);
NSURL *url = [[[NSURL alloc] initWithString:ubook]autorelease];
//NSURL *url= [NSURL URLWithString:outputString];
NSLog(#" bookmark URL IS %#",url);
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithContentsOfURL:url] autorelease];
//Initialize the delegate.
XMLParserbookm *parser = [[[XMLParserbookm alloc] initXMLParser]autorelease];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
{
NSLog(#" xml parsed suucess");
//[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//[self searchTableView];
//mytimer4=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(wipe) userInfo:nil repeats:NO];
}
else{
NSLog(#"eeror");
}
[NSThread sleepForTimeInterval:3];
[self performSelectorOnMainThread:#selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO]; // HOW TO CALL MAIN THREAD
[pool release]
}
You can try with
viewDidAppear:, this method is called after you go to a new view. Then at least, you can switch to new view, you should make sure that there is something on the screen in waiting for the xml parsing
Using Thread: You put parsing into another thread and then callback your main thread after you finish, then there will be no block at all