views:

649

answers:

4

Hi,

I've attempted to add the TopSongs parser and Core Data files into my application, and it now builds succesfully, with no errors or warning messages. However, as soon as the app loads, it crashes, giving the following reason:

UPDATE: I've got it all working, but my TableView doesn't show any data, and the app doesn't respond to the following breakpoints.

Thanks.

UPDATE: Here's the new code that doesn't respond to the breakpoints.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
    return [[fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.tableView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:self.managedObjectContext];
    [self.tableView reloadData]; 
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellIdentifier = @"SongCell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
    }
    Incident *incident = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"#%d %@", @"#%d %@"), incident.title];
    return cell;
}

- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [table deselectRowAtIndexPath:indexPath animated:YES];
    self.detailController.incident = [fetchedResultsController objectAtIndexPath:indexPath];
    [self.navigationController pushViewController:self.detailController animated:YES];
}

UPDATE: Here's the code where all instances of fetch are found.

- (Category *)categoryWithName:(NSString *)name {
    NSTimeInterval before = [NSDate timeIntervalSinceReferenceDate];
#ifdef USE_CACHING
    // check cache
    CacheNode *cacheNode = [cache objectForKey:name];
    if (cacheNode != nil) {
        // cache hit, update access counter
        cacheNode.accessCounter = accessCounter++;
        Category *category = (Category *)[managedObjectContext objectWithID:cacheNode.objectID];
        totalCacheHitCost += ([NSDate timeIntervalSinceReferenceDate] - before);
        cacheHitCount++;
        return category;
    }
#endif
    // cache missed, fetch from store - if not found in store there is no category object for the name and we must create one
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:self.categoryEntityDescription];
    NSPredicate *predicate = [self.categoryNamePredicateTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:name forKey:kCategoryNameSubstitutionVariable]];
    [fetchRequest setPredicate:predicate];
    NSError *error = nil;
    NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];
    NSAssert1(fetchResults != nil, @"Unhandled error executing fetch request in import thread: %@", [error localizedDescription]);

    Category *category = nil;
    if ([fetchResults count] > 0) {
        // get category from fetch
        category = [fetchResults objectAtIndex:0];
    } else if ([fetchResults count] == 0) {
        // category not in store, must create a new category object 
        category = [[Category alloc] initWithEntity:self.categoryEntityDescription insertIntoManagedObjectContext:managedObjectContext];
        category.name = name;
        [category autorelease];
    }
#ifdef USE_CACHING
    // add to cache
    // first check to see if cache is full
    if ([cache count] >= cacheSize) {
        // evict least recently used (LRU) item from cache
        NSUInteger oldestAccessCount = UINT_MAX;
        NSString *key = nil, *keyOfOldestCacheNode = nil;
        for (key in cache) {
            CacheNode *tmpNode = [cache objectForKey:key];
            if (tmpNode.accessCounter < oldestAccessCount) {
                oldestAccessCount = tmpNode.accessCounter;
                [keyOfOldestCacheNode release];
                keyOfOldestCacheNode = [key retain];
            }
        }
        // retain the cache node for reuse
        cacheNode = [[cache objectForKey:keyOfOldestCacheNode] retain];
        // remove from the cache
        [cache removeObjectForKey:keyOfOldestCacheNode];
    } else {
        // create a new cache node
        cacheNode = [[CacheNode alloc] init];
    }
    cacheNode.objectID = [category objectID];
    cacheNode.accessCounter = accessCounter++;
    [cache setObject:cacheNode forKey:name];
    [cacheNode release];
#endif
    totalCacheMissCost += ([NSDate timeIntervalSinceReferenceDate] - before);
    cacheMissCount++;
    return category;
}

And this one...

- (void)fetch {
    NSError *error = nil;
    BOOL success = [self.fetchedResultsController performFetch:&error];
    NSAssert2(success, @"Unhandled error performing fetch at SongsViewController.m, line %d: %@", __LINE__, [error localizedDescription]);
    [self.tableView reloadData];
}

- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController == nil) {
        NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Song" inManagedObjectContext:managedObjectContext]];
        NSArray *sortDescriptors = nil;
        NSString *sectionNameKeyPath = nil;
        if ([fetchSectioningControl selectedSegmentIndex] == 1) {
            sortDescriptors = [NSArray arrayWithObjects:[[[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:YES] autorelease], [[[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES] autorelease], nil];
            sectionNameKeyPath = @"category.name";
        } else {
            sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES] autorelease]];
        }
        [fetchRequest setSortDescriptors:sortDescriptors];
        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionNameKeyPath cacheName:@"SongsCache"];
    }    
    return fetchedResultsController;
} 
A: 

Based on the code posted and the problem description, I suspect that the categoryEntityDescription property is returning nil.

Giao
A: 
  1. your extra caching is probably a waste of cycles as Core Data performs its own caching internally. I am willing to bet you are slowing things down rather than speeding them up, not to mention the additional memory you are consuming.

  2. Where are you setting categoryEntityDescription? That is now shown in the code you posted. It is probably nil.

  3. Why are you retaining an NSEntityDescription?!? They are already in memory because of Core Data and retaining them is a waste which could lead to issues if Core Data wants to release it at some point.

update

Your caching is definitely not coming from Apple's code because they know that the cache is in Core Data.

As for the NSEntityDescription, again, do not retain the NSEntityDescription.

Are you 100% positive that the NSEntityDescription is not nil? Have you confirmed it in the debugger? Have you tested it with a freshly retrieved NSEntityDescription?

update

You need to learn to use the debugger as that will solve most of your coding issues. Put a breakpoint in this method and run your code in the debugger. Then when the execution stops on that break point you can inspect the values of the variables and learn what they are currently set to. That will confirm or deny your suspicions about what is and is not nil.

This error you are seeing happens when you fail to set the Entity in the NSFetchRequest which, based on your code, means that retained property is not being set before the code you have shown is being called.

Marcus S. Zarra
As I mentioned above, most of the code comes from Apple's TopSongs example, so I'm not sure what's going on there. As for the categoryEntityDescription, and that is set in the Category class.
Graeme
Hang on what are you referring to as the "caching"? All I've done is copy the code across from the TopSongs Apple Demo app, and rename methods to suit my project.As for the rest of your advice, I'll look into it now, thanks.
Graeme
I checked against the TopSongs app - they retain the NSEntityDescription. Interesting. As for testing that NSEntityDescription is not nil, how are you wanting me to test it? (Sorry I'm a bit of a newbie at this)
Graeme
A: 

Since you added the model file manually, is the .xcdatamodel file inside the Compile Sources step in your Target?

Go to the Targets entry in the Groups & Files pane in Xcode and click the disclosure triangle. Then click on the disclosure triangle for your app. Then check to see if it's in Compile Sources. If not, right click on Compile Sources and choose "Add -> Existing File..." and add it.

Edit based on update:

UPDATE: Here's the new code that doesn't respond to the breakpoints.

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Is your view controller set as the UITableViewDataSource/UITableViewDelegate for your UITableView? If not, these methods will not get called.

Shaggy Frog
I did add it manually, but in this case its already in the "Compile Sources" folder.
Graeme
If you look into the .app bundle that Xcode builds, is there a .mom file?
Shaggy Frog
Yeah there is - I managed to fix part of the problem though, one of my class references in the .xcdatamodel was spelt wrong :) only problem is, it now loads without crashing and supposedly parses, but the table view stays blank. Any ideas?
Graeme
And I was getting a new error (see intro edit) but I commented this out to get it to kind of work.
Graeme
Breakpoint your `fetch:` method; is it getting hit? i.e. is the `NSFetchedResultsController` actually fetching? Otherwise, set breakpoints in the various `UITableDataSource`/`UITableViewDelegate` methods. Are they getting hit? If so, what are they returning? Show your code for `numberOfSectionsInTableView:` and `tableView:numberOfRowsInSection:`.
Shaggy Frog
Alright have added code above which isn't being called during the breakpoint run. Not sure why though - rest of table code runs.
Graeme
Set edited response
Shaggy Frog
Yeah it is set to that. All other methods etc. on the page are being called apart from those two.
Graeme
Sorry - just found ViewDidLoad method isn't loading either. Added code above.
Graeme
You posted the code for `viewDidUnload`
Shaggy Frog
Whoops that's what I meant to say. It's viewDidUnload that isn't working.
Graeme
Okay, so to repeat a previous comment: what is your `NSFetchedResultsController` giving you to return in `numberOfSectionsInTableView:` and `tableView:numberOfRowsInSection:`?
Shaggy Frog
Sorry thought I had added it, but hadn't. It's up the top now.
Graeme
I'll repeat it again but only once more :) Given you say the methods are getting hit, what is your NSFetchedResultsController returning in those methods?
Shaggy Frog
Alright so you don't have to say it again, how do I get these results you want?
Graeme
Is it easier if I email you or upload to my server the files or something?
Graeme
A: 

I've seen this happen when the NSEntityDescription given to a fetch request is nil. The most likely cause of that is that you have a model entity that is named differently from the name you provided to entityForName. Barring that, it could be an error in configuration of your Core Data stack or a missing data model, but as a first step, I would recommend storing the result of entityForName in a local variable and breaking there to make sure it isn't nil.

warrenm