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.
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];
In my application i have called sharedinstance multiple time in multiple method deffinition ,
Here my code,
Method 1
-(void) showActionSheet:(id)sender forEvent:(UIEvent*)event
{
if(isQuantity==YES)
{
[[WebService sharedInstance] getQuantity:^(BOOL result)
{
if(result)
{
NSLog(#"success");
NSManagedObjectContext *context = [[DataAccessLayer sharedInstance] managedObjectContext];
Quantity = [context fetchObjectsForEntityName:NSStringFromClass([GetQuantity class]) withSortColumn:nil withSortDescending:TRUE withPredicate:nil];
NSLog(#"array ->%#",Quantity);
isQuantity=NO;
}
}];
}
popoverController1 = [[TSPopoverController alloc]initWithContentViewController:tableViewController1];
popoverController1.cornerRadius = 5;
popoverController1.titleText = #"Quantity";
popoverController1.popoverBaseColor = [UIColor blackColor];
popoverController1.popoverGradient= NO;
[popoverController1 showPopoverWithTouch:event];
}
Method 2
-(void) showActionSheetw:(id)sender forEvent:(UIEvent*)events
{
if(isSize==YES)
{
[[WebService sharedInstance] getDimension:^(BOOL result)
{
if(result){
NSLog(#"success");
NSManagedObjectContext *context = [[DataAccessLayer sharedInstance] managedObjectContext];
dime = [context fetchObjectsForEntityName:NSStringFromClass([Getdimension class]) withSortColumn:nil withSortDescending:FALSE withPredicate:nil];
NSLog(#"array ->%#",dime);
}
}];
}
popoverController2 = [[TSPopoverController alloc] initWithContentViewController:tableViewController2];
popoverController2.cornerRadius = 5;
popoverController2.titleText = #"Size";
popoverController2.popoverBaseColor = [UIColor blackColor];
popoverController2.popoverGradient= NO;
// popoverController.arrowPosition = TSPopoverArrowPositionHorizontal;
[popoverController2 showPopoverWithTouch:events];
}
EDIT
- (void) getDimension:(void (^)(BOOL))handler
{
JBContainedURLConnection *connection = [[JBContainedURLConnection alloc]init ];
[connection initWithGETUrl:IP methodName:GETDIMENSION param:nil andCompletionHandler:^(JBContainedURLConnection *connection, NSError *error, NSString *urlString, NSDictionary *userInfo, NSData *response)
{
if(error)
{
NSLog(#"Error: %#", error);
handler(FALSE);
}
else
{
if(response == nil)
handler(FALSE);
else
{
NSManagedObjectContext *context = [[DataAccessLayer sharedInstance] managedObjectContext];
NSArray *existingResults = [context fetchObjectsForEntityName:NSStringFromClass([Getdimension class]) withSortColumn:nil withSortDescending:FALSE withPredicate:nil];
for (NSManagedObject *obj in existingResults)
[context deleteObject:obj];
[[DataAccessLayer sharedInstance] saveContext];
id responseData = [self DictionaryFromResponse:response];
if(responseData == nil)
handler(FALSE);
else
{
NSLog(#"Dimension Response: %#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
NSArray *data=[responseData objectForKey:#"GetDimensionResult"];
NSLog(#"GetDimensionResult :%#",data);
for( NSDictionary *dict in data){
Getdimension *userDetails = [Getdimension newObject];
[userDetails fillFromDictionary:dict];
}
[[DataAccessLayer sharedInstance] saveContext];
handler(TRUE);
}
} }
}];
}
- (void) getQuantity:(void (^)(BOOL))handler
{
JBContainedURLConnection *connection = [[JBContainedURLConnection alloc]init ];
[connection initWithGETUrl:IP methodName:GETQUANTITY param:nil andCompletionHandler:^(JBContainedURLConnection *connection, NSError *error, NSString *urlString, NSDictionary *userInfo, NSData *response)
{
if(error)
{
NSLog(#"Error: %#", error);
handler(FALSE);
}
else
{
if(response == nil)
handler(FALSE);
else
{
NSManagedObjectContext *context = [[DataAccessLayer sharedInstance] managedObjectContext];
NSArray *existingResults = [context fetchObjectsForEntityName:NSStringFromClass([GetQuantity class]) withSortColumn:nil withSortDescending:FALSE withPredicate:nil];
for (NSManagedObject *obj in existingResults)
[context deleteObject:obj];
[[DataAccessLayer sharedInstance] saveContext];
id responseData = [self DictionaryFromResponse:response];
if(responseData == nil)
handler(FALSE);
else
{
NSLog(#"GetQuantityResult Response: %#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
NSArray *data=[responseData objectForKey:#"GetQuantityResult"];
// NSLog(#"GetDimensionResult :%#",data);
for( NSDictionary *dict in data){
GetQuantity *userDetails = [GetQuantity newObject];
[userDetails fillFromDictionary:dict];
}
[[DataAccessLayer sharedInstance] saveContext];
handler(TRUE);
}
} }
}];
}
Instance method
+ (id)sharedInstance
{
#synchronized(self)
{
if (manager == nil)
manager = [[self alloc] init];
}
return manager;
}
-(id)init
{
if(self = [super init])
{
}
return self;
}
-(NSString *)NSStringFromDictionaryUsingJSON:(id)dictionary
{
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
return [writer stringWithObject:dictionary];
}
-(id)DictionaryFromResponse:(NSData *)response
{
NSString *responseBody = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc]init];
return [parser objectWithString:responseBody error:nil];
}
sharedInstance only works one time,ie,. if i call any of the method first its worked,if calls other method second time app gets crashed.Can any one please help me to sort it out
I guess sharedInstance method is messy.
It should be
+ (id)sharedInstance
{
if (manager == nil)
manager = [[self alloc] init];
return manager;
}
Enjoy Programming !
Have you declared instance of your class as static,
Declare you class object as :
static ClassName *manager;
And the allocate the same object in your sharedInstance method.
The reason may be that the memory object was released but reference is still there in the memory.So when you execute the shared instance method it found a reference to !nil object and leads your application to crash.
This is singleton class feature of iOS(objective C)
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.
i have leaks in this code. The performane tool leaks tell me that this is in this line:
NSArray *fakeData = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"FakeData" ofType:#"plist"]];
I can't find out what is going on. The plist that i am loading have 3 NSDictionary Elements, so same as leaks in screenshot. Each Dictionary has 3 strings.
The entire code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//Ładowanie danych
if (![[FlickrFetcher sharedInstance] databaseExists]) {
NSArray *fakeData = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"FakeData" ofType:#"plist"]];
for (NSDictionary *element in fakeData) {
//Wypełnianie CoreData danymi
Photo *newPhoto = (Photo *)[NSEntityDescription insertNewObjectForEntityForName:#"Photo"
inManagedObjectContext:[[FlickrFetcher sharedInstance] managedObjectContext]];
NSLog(#"Creating Photo: %#", [element objectForKey:#"name"]);
[newPhoto setName:[element objectForKey:#"name"]];
[newPhoto setImageURL:[element objectForKey:#"path"]];
NSLog(#"Person is: %#", [element objectForKey:#"user"]);ŕŕŕ
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", [element objectForKey:#"user"]];
NSMutableArray *peopleArray = (NSMutableArray *)[[FlickrFetcher sharedInstance] fetchManagedObjectsForEntity:#"Person"
withPredicate:predicate];
NSEnumerator *enumerator = [peopleArray objectEnumerator];
Person *person;
BOOL exists = FALSE;
while (person = [enumerator nextObject]) {
NSLog(#"Person is: %#", person.name);
if ([person.name isEqualToString:[element objectForKey:#"user"]]) {
exists = TRUE;
NSLog(#"-- Person exists: %#", person.name);
[newPhoto setOwner:person];
}
}
if (!exists) {
Person *newPerson = (Person *)[NSEntityDescription insertNewObjectForEntityForName:#"Person"
inManagedObjectContext:[[FlickrFetcher sharedInstance] managedObjectContext]];
[newPerson setName:[element objectForKey:#"user"]];
NSLog(#"Person created: %#", newPerson.name);
[newPhoto setOwner:newPerson];
}
NSError *error;
if (![[[FlickrFetcher sharedInstance] managedObjectContext] save:&error]) {
NSLog(#"Unresolved error %# %#", error, [error userInfo]);
exit(-1);
}
[fakeData release];
}
}
//Person Navigation Controller
personNavigationController = [[UINavigationController alloc] init];
PersonListViewController *personListViewController = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
personListViewController.title = #"Contacts";
[personNavigationController pushViewController:personListViewController animated:NO];
[personListViewController release];
//Recent Photo Navigation Controller
recentPhotoNavigationController = [[UINavigationController alloc] init];
RecentPhotoViewController *recentPhotoViewController = [[RecentPhotoViewController alloc] init];
recentPhotoViewController.title = #"Recent";
UITabBarItem *item = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemRecents tag:1];
recentPhotoViewController.tabBarItem = item;
[item release];
[recentPhotoNavigationController pushViewController:recentPhotoViewController animated:NO];
[recentPhotoViewController release];
//Tab Bar Controller
tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = [NSArray arrayWithObjects:
personNavigationController,
recentPhotoNavigationController,
nil];
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
return YES;
}
It looks like your fakeData array is being released inside of the for loop, which seems problematic on several levels. You probably meant to release it when the loop has exited. From Leaks' perspective, the for loop might never be entered, in which case the object would be leaked.
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.