TableViewController's Table View not displaying until the data is loaded - iphone

I'm facing a strange issue. I have a method which populates an array with some data (fetchData) (quite a lot actually and it's a bit slow). I'm using the array to build the rows of the table.
I've tried calling fetchData in a number of places in my code, at various times in the construction of the view and I always seem to get the following: a black screen which is shown until the data from the array is loaded. I've called fetchData from the following:
(void)viewDidLoad;
(void)viewWillAppear:(BOOL)animated;
(void)viewDidAppear:(BOOL)animated;
Since I'm using a navigation view controller, having the app appear to hang is pretty bad looking since it gets stuck on a black screen. What I was hoping my code would achieve was displaying an empty table, with a progress indicator until the data is loaded - then refresh. Unfortunately I'm not getting this far since the view isn't being loaded no matter where I call fetchData.
Help appreciated!
P.S. To get around this problem I even tried using a TTTableViewController, but the Loading view is never displayed. Typical. sigh

Your load method must be blocking the UI. You should move it to another thread and let the data load there. You can instantiate the thread in viewDidLoad.
This is a skeleton code for that you need to (using GCD)
dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(downloadQueue, ^{
... Move all the loading part here.
dispatch_async(dispatch_get_main_queue(),^{
... Do all the UI updates, mostly, [tableView reloadData];
})
})

It possible that you could add a timer to delay the call somewhere in your viewDidAppear method. For example:
- (void)viewDidAppear:(BOOL)animated {
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(fetchData) userInfo:nil repeats:NO];
}
This will give your app time to load the UI and start your loading screen, then start fetching the data later. You can also try fetching the data in a background thread if you would prefer to go that route

I was having the same issue with a table view not loading initially, but it worked n another .m file I had. Here is the one that worked:
add this to your viewDidLoad:
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
and this to the implementation block:
#pragma mark -
#pragma mark Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"OMFrackinG" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// grouping and sorting optional
//NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"country" ascending:YES];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:#"state" ascending:YES];// was name
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1,sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
propriate.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:#"state" cacheName:nil];//#"state"
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor1 release];
[sortDescriptor2 release];
[sortDescriptors release];
}
return fetchedResultsController;
}

Related

UITableView with huge(probably 1million entries)data in iphone

I am developing an application which requires loading of more than 1 million entries through infinite scrolling in a tableview. Each time request will be sent for 1000 entries and once data is downloaded and parsed through JSON library the table is reloaded. I have implemented this through CoreData with "setFetchBatchSize = 1000".
StreamModal *modal = [[StreamModal alloc]init];
StreamModal *modal = [NSEntityDescription insertNewObjectForEntityForName:#"StreamModal" inManagedObjectContext:managedObjectContext];
if([self isNotNull:[streamDataDict objectForKey:#"_id"]])
modal.stream_id = [streamDataDict objectForKey:#"_id"];
-(void)reloaData{
#try {
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
NSLog(#"ferchresults count %d",[[_fetchedResultsController fetchedObjects]count]);
}
#catch (NSException *exception) {
NSLog(#"exception raised in reloadData in streamViewController class %#",exception);
}
#finally {
}
}
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"StreamModal" inManagedObjectContext:appDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:1000];
//[fetchRequest setFetchLimit:2000];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
fetchRequest = nil;
theFetchedResultsController = nil;
return _fetchedResultsController;
}
Here is the code i am using, when ever connectionfinishedloading data i am populating the data into NSManagedObject Class(StreamModal) and then calling reload data.Here the problem is the app is getting memory exceptions after i loaded 12000 entries in table and getting crashed. how can i load all entries without memory exception. i am new to CoreData concepts and have read the core data concepts through developer guide, but i didn't find any info related to memory handling. Please help me.
I hope you are using ARC? Because you're not releasing any initalized objects. (If not this is your answer.)
But anyway: Have you tried to use Instruments to see, which objects are increasing the memory footprint at most? That would be a good starting point.
shiva inturi,
First, I want to echo other comments that working with a single table view of a million items is really a bad user experience.
To your question:
What are you doing when the memory warning comes?
At minimum, you should be going through the objects array and trim the object graph. This is done with -refreshObject:mergeChanges:. You should also take care to not traverse your array very far. I would start from your visible objects and work both backwards and forwards until you start hitting faulted objects, by testing with -isFault.
Andrew

Add a UISegmentedController to navigation bar with NSFetchedResultsController

I am working with a UITableView that gets its data from an NSFetchedResultsController. I would like to add a UISegmentedControl to my navigation bar that would toggle the table between displaying all of the records and only the records where starred == YES.
I have read some other SO posts indicating that one way to do this is to create a second NSFetchedResultsController that has an NSPredicate with starred == YES, but it seems awfully overkill to create a second NSFetchedResultsController.
Is there a simpler way to do this?
Not according to the docs on NSFetchedResultsController. If you take a look at the documentation on the fetchRequests property, you'll see the following note:
Important: You must not modify the
fetch request. For example, you must
not change its predicate or the sort
orderings.
Since the fetchRequest property is read-only, the only option is creating a new fetched results controller.
It might be possible to change the predicate and have things work, but it's generally a bad idea to do stuff that goes explicitly against things Apple says in the documentation, because it could break in a future release.
And, beware of premature optimization! Unless you've tested it out and found out that creating a whole new fetched results controller is a big performance drain, it's not worth trying to do something in a non-recommended way.
Here's how I set a new predicate on my fetched results controller. fetchedResultsController is a property of my view controller. predicate is a private ivar of the view controller.
I already had all of the code for creating the fetched results controller on demand, so to set the predicate it's just a matter of deleted the cached one.
- (void)setPredicate:(NSPredicate *)newPredicate {
predicate = [newPredicate copy];
// Make sure to delete the cache
// (using the name from when you created the fetched results controller)
[NSFetchedResultsController deleteCacheWithName:#"Root"];
// Delete the old fetched results controller
self.fetchedResultsController = nil;
// TODO: Handle error!
// This will cause the fetched results controller to be created
// with the new predicate
[self.fetchedResultsController performFetch:nil];
[self.tableView reloadData];
}
This code if based on the boilerplate XCode generates when you start a project that uses Core Data.
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:[MyEntity entityName] inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setPredicate:predicate];
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}

UITableView not updating DataSource after change to NSFetchedResultsController

I have an UITableView populated by a NSFetchedResultsController. The initial fetch works fine. I can add, remove, modify, etc with zero problems.. But I want to add user-defined sorting to the table. I am doing this by changing the NSFetchedResultsController to use a different sortDescriptor set, and a different sectionNameKeyPath. Here is the code where I change the fetch:
-(void)changeFetchData {
fetchedResultsController = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Object" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSString *sortKey = #"sortKey";
NSString *cacheName = #"myNewCache";
BOOL ascending = YES;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sortKey cacheName:nil];
self.fetchedResultsController = aFetchedResultsController;
fetchedResultsController.delegate = self;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Fetch failed");
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
[self.tableView reloadData];
}
When I call this method, it works great. The table immediately re-orders itself to use the new section info, and the new sorting parameters. But if I add or remove items to the data, the TableView doesn't update its info, causing a crash. I can NSLog the count of the total number of objects in the fetchedResultsController, and see it increase (and decrease) but if I NSLog the return values for numberOfRowsInSection to monitor a change there, the method gets called, but the values don't change. The get the following crash (for addition, but the deletion one is similar)
Invalid update: invalid number of rows in section 2. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted). with userInfo (null)
If I restart the app, I see the added item, or do not see the deleted item, so I am modifying the datasource correctly.
Any ideas?
It's possible that the old controller is still alive. If so, it might still be calling the tableview controller as its delegate and activating the table update using it's own data.
I would suggest logging the fetched results controller object in numberOfRowsInSection to confirm that it using the new controller. You should set the old controller's delegate to nil before assigning the new one.
On one occasion, adding:
- (void)viewDidDisappear:(BOOL)animated
{
self.fetchedResultsController.delegate = nil;
}
Solved a similar issue which arises when number of rows changes but data held is still different and not up-to-date.

Dealloc'd Predicate crashing iPhone App!

To preface, this is a follow up to an inquiry made a few days ago:
https://stackoverflow.com/questions/2981803/iphone-app-crashes-when-merging-managed-object-contexts
Short Version: EXC_BAD_ACCESS is crashing my app, and zombie-mode revealed the culprit to be my predicate embedded within the fetch request embedded in my Fetched Results Controller. How does an object within an object get released without an explicit command to do so?
Long Version:
Application Structure
Platforms View Controller -> Games View Controller (Predicated upon platform selection) -> Add Game View Controller
When a row gets clicked on the Platforms view, it sets an instance variable in Games View for that platform, then the Games Fetched Results Controller builds a fetch request in the normal way:
- (NSFetchedResultsController *)fetchedResultsController{
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
//build the fetch request for Games
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Game"
inManagedObjectContext:context];
[request setEntity:entity];
//predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"platform == %#",
selectedPlatform];
[request setPredicate:predicate];
//sort based on name
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
//fetch and build fetched results controller
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[sortDescriptor release];
[sortDescriptors release];
[predicate release];
[request release];
[aFetchedResultsController release];
return fetchedResultsController;
}
At the end of this method, the fetchedResultsController's _fetch_request -> _predicate member is set to an NSComparisonPredicate object. All is well in the world.
By the time - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section gets called, the _predicate is now a Zombie, which will eventually crash the application when the table attempts to update itself.
I'm more or less flummoxed. I'm not releasing the fetched results controller or any of it's parts, and the only part getting dealloc'd is the predicate. Any ideas?
EDIT:
As a test, I added this line to the Fetched Results Controller method:
[fetchedResultsController.fetchRequest.predicate retain];
And now it doesn't crash, but that seems like a patch, not something I should be doing.
You shouldn't be releasing your predicate variable. You didn't invoke new, alloc, retain, or copy (This is the "narc" rule) to create the predicate, so you are not responsible for releasing it. That's where your zombie is coming from.

iPhone Core Data saving multiple items at once random behavior?

I have an application that reads an rss feed, parses the xml and adds it to my database using Core Data (this is so the user can see the feed even if no internet connection is available) this all works fine. The way I am doing the parsing is: on the didStartElement i create a new Entity such as:
NewsDB *newsDB = [NSEntityDescription insertNewObjectForEntityForName:#"NewsDB" inManagedObjectContext:managedObjectContext];
self.currentObject = newsDB;
and in the didendDocument i just save everything with something such as:
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSError *error = nil;
if (![managedObjectContext save:&error])
{
NSLog(#"Error saving %#", error);
}
This al works perfectly fine, in fact my program works just the way I want it now. But my question is when the managed object context gets saved the items seem to be added randomly, this is the first created object in the context may not be the first row in the database. I fixed this by adding a column that tells me the position in the xml, and then simply sorting by this column in my fetchedResultsController.
I know I could just save the context every time an item ends, but that doesn't sound like a good approach, so I just save them all at the end.
My question is why do they get added randomly?, is this the normal behavior?. Thank you.
-Oscar
The currency of Core Data are NSSet* instances. Sets are unordered, so anything you add and then fetch back will come back to you without any intrinsic ordering.
So you just need to apply an NSSortDescriptor when you initialize your NSFetchedResultsController. You can apply as many sort orderings as you like, e.g.:
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastName" ascending:YES selector:#selector(caseInsensitiveCompare:)];
NSSortDescriptor *firstNameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"firstName" ascending:YES selector:nil];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:lastNameDescriptor, firstNameDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[lastNameDescriptor release];
[firstNameDescriptor release];
...
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"keyInitial" cacheName:#"MyObjects"];
self.fetchedResultsController = aFetchedResultsController;
self.fetchedResultsController.delegate = self;
[aFetchedResultsController release];
[fetchRequest release];
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
// handle error...
}
This is normal behavior. You may have also noticed that when you create a to-many relationship that the related property is an unordered collection (NSSet).
When order matters, simply add a number attribute for sorting as you have done.