Reputation: 117
I'm a beginner of iOS. When I'm using Core Data to my sample project, it gives me a thread error.
Please help me to solve this error.
Here's my code:
-(NSFetchedResultsController*)fetchedResultController{
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Recepie" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"recepieName" ascending:YES];
NSArray *sortDescriptorArray = [[NSArray alloc]initWithObjects:sortDescriptor,nil];
request.sortDescriptors = sortDescriptorArray;
self.fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest: request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultController.delegate = self;
return self.fetchedResultController;
}
Upvotes: 0
Views: 63
Reputation: 1456
Can you please try the following code.
-(NSFetchedResultsController*)fetchedResultController{
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Recepie" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"recepieName" ascending:YES];
NSArray *sortDescriptorArray = [[NSArray alloc]initWithObjects:sortDescriptor,nil];
request.sortDescriptors = sortDescriptorArray;
self.fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest: request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultController.delegate = self;
error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return self.fetchedResultController;
}
Upvotes: 0
Reputation: 7944
When you refer to a property using dot notation like this
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
it is equivalent to calling [self fetchedResultController]
method (which is the getter for this property). And when you do this, you already are inside the getter, so the method infinitely calls itself, leading to the Stack overflow error.
You should not use the dot notation for getting a property value (using setter is OK). Use a backing variable instead:
if(_fetchedResultController != nil) {
return _fetchedResultController;
}
Upvotes: 6