Memory Leak In line of code - iphone

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];

Related

NSXMLParser parse method memory leak

I dont know why this NSXMLParser parse method is leaking.
I looked at the other similar SO question, but couldn't resolved it.
Here is my code.
- (void)parseXMLFileAtURL {
self.results = [[NSMutableArray alloc] init];
NSURL *xmlURL = [NSURL URLWithString:#"http://www.dukascopy.com/swiss/video/rss/"];
NSData *dataXml = [[NSData alloc] initWithContentsOfURL:xmlURL];
NSXMLParser *MyrssParser = [[NSXMLParser alloc] initWithData:dataXml];
[dataXml release];
[MyrssParser setDelegate:self];
[MyrssParser setShouldProcessNamespaces:NO];
[MyrssParser setShouldReportNamespacePrefixes:NO];
[MyrssParser setShouldResolveExternalEntities:NO];
[MyrssParser parse]; // memory leak here
MyrssParser.delegate=nil;
[MyrssParser release];
if(!imagesArray)
{
imagesArray = [[NSMutableArray alloc] initWithCapacity:[self.results count]];
for(int i=0;i<[results count];i++)
{
UIImage *image = [UIImage imageNamed:#"nophoto.png"];
[imagesArray addObject:image];
bImgExist[i] = NO;
}
}
}
Even After releasing my NSXMLParser object instrument still shows memory leak.
What I am missing here..
self.results = [[NSMutableArray alloc] init];
Properties take ownership (according to their declarations) of their assigned values. So the array you set this property to is retained by self (I'm assuming the property is either retain or copy here), but already has a retain count of +1 from its initialization.
Change the line to:
self.results = [NSMutableArray array];
And the memory leak should clear up.

EXC_BAD_ACCESS after audioPlayerDidFinishPlaying: called

I have a class that I call to utilize AVAudioPlayer and everything works fine and dandy when it comes to playing the audio, but when the -audioPlayerDidFinishPlaying: is called my NSLog() command says that the player is released; the problem is that the app crashes moments later. I should mention that audioPlayer is an ivar in this class. Here is the code:
-(id) initWithFileName:(NSString *)sndFileName
{
[super init];
sndFileToPlay = [[NSString alloc] initWithString:sndFileName];
return self;
}
-(void)dealloc {
[audioPlayer release];
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
[super dealloc];
}
-(void)play
{
[self playSound:sndFileToPlay];
}
-(void)playSound:(NSString *)fileName
{
NSString *fname, *ext;
NSRange range = [fileName rangeOfString:#"."];
int location = range.location;
if( location > 0 )
{
fname = [fileName substringWithRange:NSMakeRange(0, location)];
ext = [fileName substringFromIndex:location+1];
[self playSound:fname :ext];
}
}
—
-(void)playSound:(NSString *)fileName :(NSString *)fileExt
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *fileURL = [NSURL fileURLWithPath:
[mainBundle pathForResource:fileName ofType:fileExt] isDirectory:NO];
if (fileURL != nil)
{
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
[audioPlayer setDelegate:self];
[audioPlayer play];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
NSLog(#"Releasing");
[audioPlayer release];
}
There are several things wrong with your code.
For one, in your dealloc:
[audioPlayer release];
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
You are releasing the audioPlayer, then, on the released (and maybe deallocated) player you set the delegate to nil and then the property, which releases it again. Remove the [audioPlayer release];.
In your audioPlayerDidFinishPlaying:successfully: you're releasing the player as well, but you haven't set the variable to nil. That might cause a crash since by the time you access this variable again a different object might be at that memory address. Use the property instead and do it like in your dealloc:
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
Then, in playSound:: (argh, non-named second argument !) you over-release fileURL. The -[NSURL fileURLWithPath:isDirectory:] returns an autoreleased object, you may not release it.
Last but maybe not least you leak sndFileToPlay, you need to release it in your dealloc method. And instead of sndFileToPlay = [[NSString alloc] initWithString:sndFileName]; simply do sndFileToPlay = [sndFileName copy];.
You might want to read up on Objective-C memory management. It's not hard once you know the three or four rules-of-thumb.
You should clean up your code. If playSound is called several times, you are leaking AVAudioPlayer.
In your dealloc, you should put [audioPlayer release] after the two lines beneath.
Turn on NSZombieEnabled to debug, and make sure that the audioPlayer is not released when didFinish 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

if my retainCount is 4 is that bad for iphone

Updates code
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
mytimer3=[NSTimer scheduledTimerWithTimeInterval:.03 target:self selector:#selector(show) userInfo:nil repeats:NO];
NSLog(#" search is down");
//////////// rnd to hold keyboard
//ovController.view.backgroundColor = [UIColor grayColor];
self.tableView.scrollEnabled = NO;
UserText=[self.searchDisplayController.searchBar text];
myInt= UserText.length;
//int myInt= [save length];
// NSString *myStringPrt1 = [[NSString alloc] init];
// NSString *myStringPrt2 = [[NSString alloc] init];
if(UserText.length>3)
{
//[ovController.view removeFromSuperview];
//[tableView reloadData];
url=nil;
// myStringPrt1=#"http://find.php?keyword=";
NSString * myStringPrt2=UserText;
// myStringPrt1=[myStringPrt1 stringByAppendingString:myStringPrt2];
// myStringPrt1 = [myStringPrt1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// loadingView.hidden=NO;
NSString *outputString = [[NSString stringWithString:#"http://find.php?keyword="] stringByAppendingString: UserText];
outputString = [outputString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"My string is now = %#", outputString);
url= [NSURL URLWithString:outputString];
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithContentsOfURL:url] autorelease];
//Initialize the delegate.
XMLParser *parser = [[[XMLParser alloc] initXMLParser]autorelease];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
{
[super viewDidLoad];
[self searchTableView];
mytimer4=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(wipe) userInfo:nil repeats:NO];
}
}
}
Right, you have memory leaks all over the place:
NSString *myStringPrt1 = [[NSString alloc] init];
NSString *myStringPrt2 = [[NSString alloc] init];
url=nil;
myStringPrt1=#"http://wap?keyword="; //MEMORY LEAK, this will assign a new string to myStringPrt1, without releasing the first one
myStringPrt2=UserText; //MEMORY LEAK, this will assign a new string to myStringPrt2, without releasing the first one
myStringPrt1=[myStringPrt1 stringByAppendingString:myStringPrt2]; //MEMORY LEAK, this will assing an autoreleased string the myStringPrt1, without releasing the old one first.
myStringPrt1 = [myStringPrt1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //MEMORY LEAK, this will assing an autoreleased string the myStringPrt1, without releasing the old one first.
I suggest you first read the memory management guidelines as indicated by Kubi. Or, if you are feeling lazy, use this:
NSString *outputString = [[NSString stringWithString:#"http://wap?keyword="] stringByAppendingString: UserText];
outputString = [outputString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Or this:
NSString *outputString = [NSString stringWithFormat:#"http://wap?keyword=%#",UserText];
outputString = [outputString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Don't pay any attention to your retain count. That number will fluctuate for reasons entirely out of your control and trying to determine why the number is what it is will drive you crazy (and not do you any good).
Follow proper Obj-C memory management guidelines, use the leaks detector in Instruments, and run the static analyzer when you build. If you do all that, you'll be fine.
No depending on your requirement and object allocation, your retain count will definitely increase. But the main thing you need to keep in mind that release all the allocated object at proper place and proper time.

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

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.