i am working on a fishing app these days and i am getting a memory leak problem
-(void)requestFinished:(ASIFormDataRequest *) request {
if(hud != nil){
[hud show:NO];
[hud release];
hud = nil;
}
isLoading = NO;
self.responseText = [request responseString];
[self parseXml]; //I am getting leak here
if ( [self.responseText hasPrefix:#"<result>"]) {
UIAlertView *info = [[[UIAlertView alloc] initWithTitle:#" " message:#"Limited Internet access, please find a stronger signal in the area" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]autorelease];
[info show];
}
if (!isRefreshButtonClicked) {
[UIAccelerometer sharedAccelerometer].delegate = self;
[NSThread detachNewThreadSelector:#selector(parseXml) toTarget:self withObject:nil];
} }
This is my function...
-(void) parseXml
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
_fishes = [[fishes parseXml:self.responseText] retain];
[self performSelectorOnMainThread:#selector(parseXmlDone) withObject:nil waitUntilDone:YES];
[pool release];
Here _fishes is an array which is getting a value from a array return type function.....and here is that function...
+(NSMutableArray *)parseXml:(NSString *)xmlString {
//xmlString = [xmlString stringByReplacingOccurrencesOfString:#"&" withString:#""];
const char *cString = [xmlString UTF8String];
NSMutableArray *fishes = [NSMutableArray array];
NSData *xmlData = [NSData dataWithBytes:cString length:strlen(cString)];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
if (doc == nil) { return nil; }
//parseXml
NSArray *_fishes = [doc.rootElement elementsForName:#"fishery"];
for (GDataXMLElement *_fish in _fishes) {
NSMutableDictionary *fish = [NSMutableDictionary dictionary];
NSArray *ids = [_fish elementsForName:#"id"];
if ([ids count]>0) {
GDataXMLElement *firstId = (GDataXMLElement *)[ids objectAtIndex:0];
[fish setValue:firstId.stringValue forKey:#"id"];
} else continue;
NSArray *names = [_fish elementsForName:#"name"];
if ([names count]>0) {
GDataXMLElement *firstName = (GDataXMLElement *)[names objectAtIndex:0];
[fish setValue:firstName.stringValue forKey:#"name"];...........
........
else continue;
NSArray *distances = [_fish elementsForName:#"distance"];
if ([distances count]>0) {
GDataXMLElement *distance = (GDataXMLElement *)[distances objectAtIndex:0];
[fish setValue:distance.stringValue forKey:#"distance"];
}else continue;
[fishes addObject:fish];
}
[doc release];
return fishes;
}
#end
I hope u guys will understand my problem...thanx
In -parseXml,
_fishes = [[fishes parseXml:self.responseText] retain];
will leak any previous object _fishes was pointing to in case -parseXml is sent more than once. You could use a retain property instead of an instance variable, or a setter method that releases the previous object, or release the previous object before assigning a new (retained) object to _fishes.
Related
In a view I am showing images which I am fetching from coredata, The images I am showing using carousel classes. In the same view I have facebook button which will navigate me to another screen. When I am clicking the Facebook button then the action is not getting performed, after the images are loaded only the next screen is coming, the button action is not getting called as soon as I click on it.
In viewDidLoad I have called:
[self performSelectorInBackground:#selector(popularImages) withObject:nil];
The popularImages method:
- (void)popularImages
{
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Deals"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ispopular == 1"];
[request setPredicate:predicate];
NSLog(#"popular Hypes called");
[self.managedObjectContext executeFetchRequest:request returnManagedObjectIDs:NO onSuccess:^(NSArray *deals) {
deals123 = [[NSMutableArray alloc] initWithArray:deals];
ij = 1;
for (Deals *deals in deals123) {
customizedMessage = [deals valueForKeyPath:#"txtmsgrec"];
dealIdString = [deals valueForKeyPath:#"dealsId"];
descriptionStr = [deals valueForKeyPath:#"dealdescription"];
captionStrArray = [deals valueForKeyPath:#"dealsassets.caption"];
[customizedMessageDict setObject:customizedMessage forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:customizedMessageDict forKey:#"dealsmessage"];
[dealsIdDict setObject:dealIdString forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsIdDict forKey:#"dealsId"];
NSDictionary *dict = [NSDictionary dictionaryWithObject:captionStrArray forKey:#"caption"];
NSArray *captionTemparr = [[dict objectForKey:#"caption"] allObjects];
NSArray *assets = [deals valueForKeyPath:#"dealsassets.dealassetid"];
NSDictionary *dealassetidDict = [NSDictionary dictionaryWithObject:assets forKey:#"dealassetid"];
NSArray *dealassetidTemparr = [[dealassetidDict objectForKey:#"dealassetid"] allObjects];
[dealsUrlDict setObject:[[dealassetidDict objectForKey:#"dealassetid"] allObjects] forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsUrlDict forKey:#"delasURL"];
[dealsdescriptionDict setObject:descriptionStr forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsdescriptionDict forKey:#"dealsDescription"];
[dealscaptionDict setObject:captionTemparr forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealscaptionDict forKey:#"dealscaption"];
ij++;
}
NSArray *array = [[dealDict valueForKey:#"delasURL"]allKeys];
NSLog(#"allKeys]class %#",[[[dealDict valueForKey:#"delasURL"]allKeys]class]);
NSDictionary *dealurlDict = [dealDict valueForKey:#"delasURL"];
NSDictionary *dealDescDict = [dealDict valueForKey:#"dealsDescription"];
NSDictionary *dealCaptionDict = [dealDict valueForKey:#"dealscaption"];
NSDictionary *dealIDDict = [dealDict valueForKey:#"dealsId"];
NSDictionary *dealMessageDict = [dealDict valueForKey:#"dealsmessage"];
for(int i=0;i<[array count];i++)
{
NSString *keyvalue = (NSString *)[array objectAtIndex:i];
NSString *dealId = [dealIDDict valueForKey:keyvalue];
NSArray *dealUrl = [dealurlDict valueForKey:keyvalue];
NSString *dealdesc = [dealDescDict valueForKey:keyvalue];
NSArray *dealcaption = [dealCaptionDict valueForKey:keyvalue];
NSString *dealMessage = [dealMessageDict valueForKey:keyvalue];
if([dealUrl count] == [dealcaption count])
{
//[dealUrl enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop)
for(int j = 0; j<[dealUrl count]; j++)
{
PopularHypesModal *dobject = [[PopularHypesModal alloc]init];
dobject.dealsID = dealId;
dobject.dealDescription = dealdesc;
dobject.dealcaption = [dealcaption objectAtIndex:j];
dobject.dealsUrl = [dealUrl objectAtIndex:j];
dobject.dealsMessage = dealMessage;
[self.items addObject:dobject];
[dobject release];
}
}
else
{
//[dealUrl enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop)
for(int j=0;j<[dealUrl count];j++)
{
PopularHypesModal *dobject=[[PopularHypesModal alloc]init];
dobject.dealsID = dealId;
dobject.dealDescription = dealdesc;
dobject.dealsMessage = dealMessage;
if([dealcaption count]>0)
{
dobject.dealcaption =[dealcaption objectAtIndex:0];
}
dobject.dealsUrl=[dealUrl objectAtIndex:j];
[self.items addObject:dobject];
[dobject release];
}
// ];
}
}
//];
carousel.dataSource = self;
carousel.delegate = self;
}onFailure:^(NSError *error) {
NSLog(#"Error fetching: %#", error);
popularHypes = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Server Problem" message:#"Sorry, There is some Error with server,Please try after some time" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
ij++;
}];//1st
[dealDict retain];
}
The button I have added in xib, How can I overcome this?
Running on a background thread shouldn't give you any issues, unless you try to update a UI element from that same background thread. Be sure to forward any UI-related activities to the main thread. For example:
- (void)viewWillAppear:(BOOL)animated {
[self performSelectorInBackground:#selector(refreshTableView)];
[super viewWillAppear:animated];
}
- (void)refreshTableView {
// YourCode
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
}
hope it's helpful :)
Please try this NSThread method
[NSThread detachNewThreadSelector:#selector(RunMethodEvenWhenMinimized) toTarget:self withObject:dict];
I have ~60000 values in my DB.
I must to keep them all. But while inserting values I get exc_bad_access.
Here is my code:
if (context == nil)
{
context = [(radioAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", context);
}
[self performSelectorOnMainThread:#selector(deleteAllFromDB) withObject:nil waitUntilDone:YES];
// here is JSON parsing
int i=0;
#synchronized(self)
{
NSLog(#"Start");
NSEntityDescription *entity = [[NSEntityDescription entityForName:#"Station" inManagedObjectContext:context] autorelease];
for (NSString*string in stations)
{
if (![string isEqualToString:#""])
{
Station*station = [[[Station alloc] initWithEntity:entity insertIntoManagedObjectContext:nil] retain];
NSError *err = nil;
id parsedData = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(#"error is %#", [err localizedDescription]);
}
[station setName:[parsedData objectForKey:#"nm"]];
[station setBit: [parsedData objectForKey:#"btr"]];
[station setEnabled: [NSNumber numberWithInt:1]];
//encoding id of the station
scanner = [NSScanner scannerWithString:[parsedData objectForKey:#"id"]];
[scanner scanHexInt:&tempInt];
NSNumber *numb = [[NSNumber alloc]initWithInt:i];
[station setNumber: [NSNumber numberWithInt:[numb intValue]]];
//encoding country ID
numb = [NSNumber numberWithInt:i];
[station setCountryID: [NSNumber numberWithInt:[numb intValue]]];
//encoding genre ID
numb = [NSNumber numberWithInt:i];
[station setGenerID:[NSNumber numberWithInt:[numb intValue]]];
[station setOrder:[NSNumber numberWithInt:i]];
[context insertObject:station];
float k = [stations count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
i++;
[scanner release];
[numb release];
[station release];
[parsedData release];
}
}
[context save:nil];
[entity release];
NSLog(#"Stop");
NSEntityDescription *entityGen = [NSEntityDescription entityForName:#"Genre" inManagedObjectContext:context];
NSURL* urlForGenre = [NSURL URLWithString:#"xxx.xxx"];
NSData *genres = [[NSData alloc] initWithContentsOfURL:urlForGenre];
NSError *err = nil;
NSArray *parsedGenres = [NSJSONSerialization JSONObjectWithData:genres options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
for (int i =0; i<parsedGenres.count; i++)
{
Genre*gen = [[Genre alloc] initWithEntity:entityGen insertIntoManagedObjectContext:nil];
gen.name = [[parsedGenres objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedGenres objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
gen.number = [NSNumber numberWithInt:[numb integerValue]];
float k = [parsedGenres count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:gen];
[gen release];
}
[entityGen release];
[context save:nil];
NSEntityDescription *entityCon = [NSEntityDescription entityForName:#"Country" inManagedObjectContext:context];
NSURL* urlForCoun = [NSURL URLWithString:#"yyy.yyy"];
NSData *countr = [[NSData alloc] initWithContentsOfURL:urlForCoun];
err = nil;
NSArray *parsedCountr = [NSJSONSerialization JSONObjectWithData:countr options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
NSMutableArray* temp = [[NSMutableArray alloc] init];
for (int i =0; i<parsedCountr.count; i++)
{
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
countr.name = [[parsedCountr objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedCountr objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
countr.number = [NSNumber numberWithInt:[numb integerValue]];
[temp addObject:countr];
float k = [parsedCountr count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:countr];
[countr release];
}
[context save:nil];
If my app doesn't crash, yes, it happens not by every launch. It crashes on:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Please help! And sorry for my terrible English.
Update:
On:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Thread 7: EXC_BAD_ACCESS (code=1, address=0x3f800008)
Other error is exc_bad_access too. But with code=2 and on other thread.
Update 2:
I enabled zombies mode in scheme of my debug. Nothing happened.
Update 3:
I think I have problems with memory.
GuardMalloc: Failed to VM allocate 4128 bytes
GuardMalloc: Explicitly trapping into debugger!!!
You can't pass nil as managedObjectContext parameter to initWithEntity:insertIntoManagedObjectContext: method. Try changing this:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
to this
// pass managed object context parameter
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:context];
Based on the documentation and my experience you can pass nil as managedObjectContext.
I was also getting an EXC_BAD_ACCESS and it came that the reason was that I was not retaining the managed object model(I was only creating a model to get the entity description and then it was released).
In particular, this is what I was doing:
In a test class, in the setUp method:
- (void)setUp
{
[super setUp];
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *modelURL = [bundle URLForResource:#"TestDatamodel" withExtension:#"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
STAssertNotNil(model, nil);
_entity = [[model entitiesByName] objectForKey:NSStringFromClass([MyEntity class])];
STAssertNotNil(_entity, nil);
// ...
}
Then in a test method I was creating a managed object without a context like this:
NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:_entity insertIntoManagedObjectContext:nil];
And I was getting EXC_BAD_ACCESS here.
The solution was to add an ivar to the test class to keep a reference to the managed object model.
Hello I am parsing a RSS And Atom feeds, and my question is how can I check for < img > and < url > tags in < description >?
There must be some sort of check. Thanks.
Here is how I parse them:
- (NSArray *)parseFeed:(NSURL *)feedURL{
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:feedURL];
GDataXMLDocument *xmlParse = [[GDataXMLDocument alloc] initWithData:data error:&error];
GDataXMLElement *rootElement = xmlParse.rootElement;
NSArray *array = [[NSArray alloc] init];
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
array = [self parseRSSFeed:rootElement];
return array;
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
array = [self parseAtomFeed:rootElement];
return array;
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
return nil;
}
}
-(NSArray *)parseRSSFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [item valueForChild:#"title"];
itemF.description = [item valueForChild:#"description"];
NSLog(#"IMAGE - %#", [item valueForChild:#"img"]);
itemF.dateString = [item valueForChild:#"pubDate"];
itemF.link = [NSURL URLWithString:[item valueForChild:#"link"]];
itemF.dateString = [item valueForChild:#"updated"];
itemF.author = [item valueForChild:#"author"];
[entries addObject:itemF];
NSLog(#"RSS - %#", itemF.title);
}
}
NSArray *RSSArray = [entries copy];
return RSSArray;
}
-(NSArray *)parseAtomFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *entry = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *entryElement in entry) {
// NSArray *items = [channel elementsForName:#"item"];
//for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [entryElement valueForChild:#"title"];
itemF.description = [entryElement valueForChild:#"summary"];
NSArray *links = [entryElement elementsForName:#"link"];
for (GDataXMLElement *link in links) {
itemF.link = [NSURL URLWithString:[[link attributeForName:#"href"] stringValue]];
}
itemF.dateString = [entryElement valueForChild:#"updated"];
NSArray *authors = [entryElement elementsForName:#"author"];
for (GDataXMLElement *authorElement in authors) {
itemF.author = [authorElement valueForChild:#"name"];
}
[entries addObject:itemF];
NSLog(#"Atom - %#", itemF.title);
}
NSArray *atomArray = [entries copy];
return atomArray;
}
I am parsing them using GDataXMLParser, and my own parser class.
Do it like this:
NSString *Str=[item valueForChild:#"description"];
NSArray *tmp=[Str componentsSeparatedByString:#"<Img>"];
if([tmp count]>1){
NSString *urlstr=[[tmp objectatindex:1] stringByReplacingOccurrencesOfString:#" </Img>" withString:#""];
}
Now urlstr contains your image url.
Enjoy
I thought that
itemF.description = [item valueForChild:#"description"];
is NSString. So you can use componentsSeparatedByString with "your tag".
It will return array. In array at postion 1 you will get your img url.
This url has closing bracket "your closing tag".
Replace "your closing tag" with space. You will get image url.
Hope, this will help you.
I am not able to find a way to remove a leak detected by leaks tool.
Here is my problem...
I have a singleton object in my delegate which stores data on a global level. Now, I have a array of objects which i maintain here and add or modify it from controllers.
Below is a function which fills the objects and sets the above global array,
Now, the highlighted lines(marked by //LEAK) are where the leaks tool tell me its a leak. I require this array for my session. I release the array at the end when i logout.
Should i be worried about this kind leak?
-(LayoutInfo *) fillLayout: (GDataXMLElement *) layoutElement {
LayoutInfo *layout = [[LayoutInfo alloc] init];
layout.dataTableCount = 0;
layout.chartsCount = 0;
NSArray *templateNameArr = [layoutElement elementsForName:#"TemplateName"];
NSMutableArray *chartElements = [[NSMutableArray alloc] init]; // LEAK
NSMutableArray *dtElements = [[NSMutableArray alloc] init];
NSArray *charts = [layoutElement elementsForName:#"chart"]; // LEAK
if (charts.count > 0) {
for (GDataXMLElement *singleChart in charts) {
chart *chartInfo = [[chart alloc] init]; // LEAK
layout.chartsCount = layout.chartsCount + 1;
NSArray *imageName = [singleChart elementsForName:#"imageName"];
if (imageName.count > 0) {
GDataXMLElement *imageNameStr = (GDataXMLElement *) [imageName objectAtIndex:0];
chartInfo.imageName = imageNameStr.stringValue; // LEAK
}
NSArray *imagePath = [singleChart elementsForName:#"imagePath"];
if (imagePath.count > 0) {
GDataXMLElement *imagePathStr = (GDataXMLElement *) [imagePath objectAtIndex:0];
chartInfo.imagePath = imagePathStr.stringValue; // LEAK
}
NSArray *imageFileName = [singleChart elementsForName:#"imageFileName"];
if (imageFileName.count > 0) {
GDataXMLElement *imageFileNameStr = (GDataXMLElement *) [imageFileName objectAtIndex:0];
chartInfo.imageFileName = imageFileNameStr.stringValue;
}
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:chartInfo.imagePath]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
stringByAppendingPathComponent:chartInfo.imageFileName]];
[request setDidFinishSelector:#selector(fillLayout_requestDone:)];
[request setDidFailSelector:#selector(fillLayout_requestWentWrong:)];
[request startSynchronous];
NSString *imagePath1 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName];
if([[NSFileManager defaultManager] fileExistsAtPath:imagePath1]) {
NSLog(#" --- IMAGE SAVED -- %#", imagePath1);
}
[chartElements addObject:chartInfo];
} //for
layout.chartElement = chartElements; // THIS IS WHERE I ASSIGN THE GLOBAL ARRAY
//[chartElements release];
}
return layout;
}
-(LayoutInfo *) fillLayout: (GDataXMLElement *) layoutElement {
LayoutInfo *layout = [[LayoutInfo alloc] init];
layout.dataTableCount = 0;
layout.chartsCount = 0;
NSArray *templateNameArr = [layoutElement elementsForName:#"TemplateName"];
NSMutableArray *chartElements = [[NSMutableArray alloc] init]; // LEAK
//NSMutableArray *dtElements = [[NSMutableArray alloc] init];
NSArray *charts = [layoutElement elementsForName:#"chart"]; // LEAK
if (charts.count > 0) {
for (GDataXMLElement *singleChart in charts) {
chart *chartInfo = [[chart alloc] init]; // LEAK
layout.chartsCount = layout.chartsCount + 1;
NSArray *imageName = [singleChart elementsForName:#"imageName"];
if (imageName.count > 0) {
GDataXMLElement *imageNameStr = (GDataXMLElement *) [imageName objectAtIndex:0];
chartInfo.imageName = imageNameStr.stringValue; // LEAK
}
NSArray *imagePath = [singleChart elementsForName:#"imagePath"];
if (imagePath.count > 0) {
GDataXMLElement *imagePathStr = (GDataXMLElement *) [imagePath objectAtIndex:0];
chartInfo.imagePath = imagePathStr.stringValue; // LEAK
}
NSArray *imageFileName = [singleChart elementsForName:#"imageFileName"];
if (imageFileName.count > 0) {
GDataXMLElement *imageFileNameStr = (GDataXMLElement *) [imageFileName objectAtIndex:0];
chartInfo.imageFileName = imageFileNameStr.stringValue;
}
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:chartInfo.imagePath]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
stringByAppendingPathComponent:chartInfo.imageFileName]];
[request setDidFinishSelector:#selector(fillLayout_requestDone:)];
[request setDidFailSelector:#selector(fillLayout_requestWentWrong:)];
[request startSynchronous];
NSString *imagePath1 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName];
if([[NSFileManager defaultManager] fileExistsAtPath:imagePath1]) {
NSLog(#" --- IMAGE SAVED -- %#", imagePath1);
}
[chartElements addObject:chartInfo];
[chartInfo release]; // it's retained in chartElements until removed, or until chartElements is deallocced
} //for
if(layout.charElement){
[layout.charElement release]; // you should however consider in making charElement property as retain;
layout.charElement = nil; // this isn't required here (since you're assigning it a new value), but you should usually set it to nil after a release to prevent EXC_BADACCESS
}
layout.chartElement = chartElements; // THIS IS WHERE I ASSIGN THE GLOBAL ARRAY
//[chartElements release];
}
return [layout autorelease]; // in case you don't want it autoreleased you should call your method something like: createFilledLayout ('create' is usually used so anyone that uses the method knows it's responsible for releasing the return value)
}
you should have a look at Memory Management Programming Guide
I'm using TouchXML to parse an XML-stream the following way:
CXMLDocument *parser = [[CXMLDocument alloc] initWithXMLString:responseString options:0 error:nil];
[responseString release];
// array holding all the nodes
NSArray *directionNodes = [parser nodesForXPath:#"//direction" error:nil];
NSArray *linieNodes = [parser nodesForXPath:#"//route" error:nil];
NSArray *timeNodes = [parser nodesForXPath:#"//time" error:nil];
for (int i = 0; i < [directionNodes count]; i++) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CXMLElement *direction = [directionNodes objectAtIndex:i];
CXMLElement *route = [linieNodes objectAtIndex:i];
CXMLElement *time = [timeNodes objectAtIndex:i];
// if rows are empty, stop it
if ([[direction stringValue] isEqualToString:#""]) {
break;
}
AbfahrtszeitResult *result = [[AbfahrtszeitResult alloc] init];
[result setLinie:[route stringValue]];
[result setZiel:[direction stringValue]];
[result setZeit:[time stringValue]];
[mutableAbfahrten addObject:result];
[result release];
[pool release];
}
Now, I always get a memory leak in the "stringValue"-line... am I doing something wrong or is it TouchXML?
Thanks a lot,
Stefan
-(NSString *) linie {
return linie;
}
- (void) setLinie:(NSString *)textValue {
[textValue retain];
[linie release];
linie = textValue;
}
-(NSString *) ziel {
return ziel;
}
-(void) setZiel:(NSString *)textValue {
[textValue retain];
[ziel release];
ziel = textValue;
}
-(NSString *) zeit {
return zeit;
}
-(void) setZeit:(NSString *)textValue {
[textValue retain];
[zeit release];
zeit = textValue;
}
+ (NSString *) cleanUpString:(NSString *) cleanme {
NSMutableString *tempString = [[NSMutableString alloc] initWithString:cleanme];
[tempString replaceOccurrencesOfString:#" " withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
[tempString replaceOccurrencesOfString:#" " withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
return [tempString autorelease];
}
You have at least one leak when [[direction stringValue] isEqualToString:#""] is true as you break out of the for loop without releasing your AutoreleasePool. Beyond that, we'd need to see the implementation of your AbfahrtszeitResult class to see how your Linie setter is defined.