Assume I have 3 files in my project:
- data model file, dealing with Core Data and fetching info
- viewController 1
- viewController 2
In the model file I get results us follows:
- (NSArray *) getColonyData
{
NSManagedObjectContext *cxt = [self managedObjectContext];
NSEntityDescription *colonyDesc = [NSEntityDescription entityForName:@"Colony" inManagedObjectContext:cxt];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:colonyDesc];
NSError *error;
NSArray *colonyResults = [cxt executeFetchRequest:request error:&error];
return colonyResults;
}
I run this part of code in viewDidLoad section of the 1st viewController and I get proper results:
NSArray *colonyResults = [model getColonyData];
if (colonyResults != nil)
{
colonyName.text = [[colonyResults objectAtIndex:0] valueForKey:@"name"];
}
else
{
colonyName.text = @"nothing setup yet";
}
Then I move via a segue to a 2nd viewController, when I execute exactly same code (of course updating different UI elements). But this time the result is nil. What am I doing wrong here? Should I release results manually first? No other errors appear.
Thanks.
As suggested in comments:
experimentModel *model;doesn’t assign anything; it just declares that a variable exists. Somewhere, you must be setting model to an actual object for the first controller (and probably not doing that for the second one).Sending messages to nil objects is a common way to not get the results one was expecting. 🙂