NSManagedObjectContext outside the PersistentDocument - objective-c

I've created a Document Application for Mac OSX to work with CoreDataModel.
Now I'm trying to programmatically save a value in the coredata when a button is clicked.
I'm able to save a value when the app start:
- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
NSManagedObjcetContext *moc = [self managedObjectContext];
NSSet *session = [moc fetchObjectsForEntityName:#"Sessions" withPredicate:nil];
NSLog(#"%d", (int)[session count]);
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Sessions"
inManagedObjectContext:moc];
[obj setValue:#"TEST" forKey:#"name"];
[obj setValue:[NSDate dateWithTimeIntervalSinceReferenceDate:112700] forKey:#"start"];
[obj setValue:[NSDate dateWithTimeIntervalSinceReferenceDate:118700] forKey:#"stop"];
}
but I want to save a value of a counter inside a NSObject. So I've tried to create a function in the PersistentDocument like the previous passing a value, but the count of the coredata elements is 0, so I think that is not referencing to the correct Entity.
Can anyone explain me how to do that or how this can works?
Thanks
Ale
EDIT:
I'll try to be more clear.
I've a chrono counter with START and STOP button. I want to save the value of the timer, when is stopped, in the coredata using another button SAVE. The managing of the counter is in an NSObject CounterObject.
How can I do it? Now I'm able to write in the core data only from the PersistentDocument caling a function from windowControllerDidLoadNib. I want to call a function that write in the coredata my counter value, but if I call the function in the PersistentDocument from the CounterObject the log that I've inserted show 0 elements instead of 4. So it's not correctly passed.
Here is the code:
// Document
#import "Document.h"
#import "NSManagedObjectContext.h"
#implementation Document
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
- (NSString *)windowNibName
{
// Override returning the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
return #"Document";
}
- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
[self saveTimeMOC:[NSDate dateWithString:#"11:23:34"]];
}
-(IBAction)saveTimeMOC:(NSDate *)time {
NSManagedObjectContext *moc = [self managedObjectContext];
NSSet *session = [moc fetchObjectsForEntityName:#"Sessions" withPredicate:nil];
NSLog(#"%d", (int)[session count]);
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Sessions"
inManagedObjectContext:moc];
[obj setValue:#"TEST" forKey:#"name"];
[obj setValue:time forKey:#"start"];
[obj setValue:[NSDate dateWithTimeIntervalSinceReferenceDate:118700] forKey:#"stop"];
}
+ (BOOL)autosavesInPlace
{
return YES;
}
#end
// CounterObject
#import "CounterObject.h"
#import "Document.h"
#implementation CounterObject
#synthesize contText, startButton, stopButton;
-(id)init {
self = [super init];
if (self) {
}
return self;
}
- (IBAction)startContatore:(id)sender {
stopButton.title = #"Stop";
[stopButton setEnabled:YES];
[startButton setEnabled:NO];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(gestioneTimer) userInfo:nil repeats:YES];
}
- (IBAction)stopContatore:(id)sender {
if (timer != nil) {
[timer invalidate];
timer = nil;
}
if (stopButton.title != #"Reset") {
[startButton setEnabled:YES];
stopButton.title = #"Reset";
startButton.title = #"Continue";
} else if (stopButton.title == #"Reset") {
stopButton.title = #"Stop";
[stopButton setEnabled:NO];
startButton.title = #"Start";
timerCont = 0;
contText.stringValue = [NSString stringWithFormat:#"00:00"];
}
}
- (void)gestioneTimer {
timerCont += 1;
int minutes = floor(timerCont/60);
int seconds = trunc(timerCont - minutes * 60);
contText.stringValue = [NSString stringWithFormat:#"%02i:%02i", minutes, seconds];
}
- (IBAction)saveTime:(id)sender {
Document *moc = [[Document alloc] init];
[moc saveTimeMOC:[NSDate dateWithString:#"13:45:22"]];
}

If you want to add an Object to core data, you can do this :
- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
NSManagedObjcetContext *moc = [self managedObjectContext];
// But be sure that [self managedObjectContext] is the correct one; you can do this to see if //it's not a null value : NSLog(#"%#",[self managedObjectContext]);
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Sessions"
inManagedObjectContext:moc];
[obj setValue:#"TEST" forKey:#"name"];
[obj setValue:[NSDate dateWithTimeIntervalSinceReferenceDate:112700] forKey:#"start"];
[obj setValue:[NSDate dateWithTimeIntervalSinceReferenceDate:118700] forKey:#"stop"];
}
And a request for Core Data is :
-(voi)testRequestCoreData {
NSError *error =nil;
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init]autorelease];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Sessions" inManagedObjectContext:moc];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
....
}

Related

UICollectionViewController with NSFetchedResultsController broke, when update property of all objects, if controller sorted on this property

I have UICollectionViewController , It is collection view for some Objects at the map. So, I can update one item in fetched result (for example set LIKE for one of this Object). It is work well. I see changes immediately.
But if trying to update property "Distance" of all Objects, and same time controller are sorted on this property. Fetched result doesn't updated automatically. And then, while scrolling, reused Cells not updated, and I can see only Cells, that was on display, before I was started update property for all Objects. If I TouchUpInside first Cell in a row, for example it would be Object 123, controller open detail page of different Object, that Object, that should stay at this position after collectionView reloadData.
Incase I'm change Sort Descriptors from [fetchRequest setSortDescriptors:#[distanceAscending]];
to [fetchRequest setSortDescriptors:#[titleAscending]];
or [fetchRequest setSortDescriptors:#[titleAscending, distanceAscending]];
It is work well.
Incase I'm change property "Distance" of only one Object.
It is work well. Controller sort Cells as it should.
Incase I'm change property "Distance" of Objects not fetched this time.
It is work well.
Incase I'm close this controller, and open again [fetchRequest setSortDescriptors:#[distanceAscending]]; working as it should
I'm tying to reload CollectionViewController different ways,
[self.collectionView reloadData]; and reloadwithPredicateDefault. But same result.
I'm tying to change Managed Object Context NSPrivateQueueConcurrencyType and NSMainQueueConcurrencyType. But same result.
MapObjectCollectionViewController.h
#interface MapObjectCollectionViewController : UICollectionViewController
MapObjectCollectionViewController.m
#interface MapObjectCollectionViewController ()<NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSManagedObjectContext* managedObjectContext;
#property (strong, nonatomic) NSPredicate * predicate1;
#property (strong, nonatomic) NSPredicate * predicate2;
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription* description =
[NSEntityDescription entityForName:#"MapObj"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:description];
_predicate1 = [NSPredicate predicateWithFormat:#"types.typeObjValue IN %#", self.selectionsTypes];
_predicate2 = [NSPredicate predicateWithFormat:#"wiFi >= %i", 0];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:#[_predicate1, _predicate2]];
[fetchRequest setPredicate:predicate];
NSSortDescriptor* titleAscending = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES];
NSSortDescriptor* distanceAscending = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:NO];
[fetchRequest setSortDescriptors:#[distanceAscending]];
// [fetchRequest setSortDescriptors:#[titleAscending, distanceAscending]];
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
}
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
NSMutableDictionary *change = [[NSMutableDictionary alloc] init];
switch(type) {
case NSFetchedResultsChangeInsert:
change[#(type)] = newIndexPath;
break;
case NSFetchedResultsChangeDelete:
change[#(type)] = indexPath;
break;
case NSFetchedResultsChangeUpdate:
change[#(type)] = indexPath;
break;
case NSFetchedResultsChangeMove:
change[#(type)] = #[indexPath, newIndexPath];
break;
}
[_itemChanges addObject:change];
}
- (void)reloadwithPredicateDefault {
[NSFetchedResultsController deleteCacheWithName:nil];
self.fetchedResultsController = nil;
[self.fetchedResultsController performFetch:nil];
[self.collectionView reloadData];
}
#pragma mark - UICollectionViewDataSource
- (NSManagedObjectContext*) managedObjectContext {
if (!_managedObjectContext) {
_managedObjectContext = [[DataManager sharedManager] managedObjectContext];
}
return _managedObjectContext;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
[self.collectionView performBatchUpdates:^{
for (NSDictionary *change in self->_sectionChanges) {
[change enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSFetchedResultsChangeType type = [key unsignedIntegerValue];
switch(type) {
case NSFetchedResultsChangeInsert:
[self.collectionView insertSections:[NSIndexSet indexSetWithIndex:[obj unsignedIntegerValue]]];
break;
case NSFetchedResultsChangeDelete:
[self.collectionView deleteSections:[NSIndexSet indexSetWithIndex:[obj unsignedIntegerValue]]];
break;
case NSFetchedResultsChangeMove:
break;
case NSFetchedResultsChangeUpdate:
break;
}
}];
}
for (NSDictionary *change in self->_itemChanges) {
[change enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSFetchedResultsChangeType type = [key unsignedIntegerValue];
switch(type) {
case NSFetchedResultsChangeInsert:
[self.collectionView insertItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeDelete:
[self.collectionView deleteItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeUpdate:
[self.collectionView reloadItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeMove:
[self.collectionView moveItemAtIndexPath:obj[0] toIndexPath:obj[1]];
break;
}
}];
}
} completion:^(BOOL finished) {
self->_sectionChanges = nil;
self->_itemChanges = nil;
}];
}
DataManager.h
#property (readonly, strong, nonatomic) NSManagedObjectContext *mainPrivateManagedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
+ (DataManager*)sharedManager;
DataManager.m
#implementation DataManager
#synthesize mainPrivateManagedObjectContext = _mainPrivateManagedObjectContext;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
+(DataManager*) sharedManager{
static DataManager* manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[DataManager alloc] init];
});
return manager;
}
#pragma mark - Core Data stack
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"ProjectName" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"ProjectName.sqlite"];
NSError *error = nil;
// NSString *failureReason = #"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES} error:&error]) {
NSLog(#"error = %#", error);
// Report any error we got.
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; //Удалить старую базу
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]; //Создать базу заново
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
// . NSLog(#"get managedObjectContext");
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_mainPrivateManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_mainPrivateManagedObjectContext setPersistentStoreCoordinator:coordinator];
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setParentContext:_mainPrivateManagedObjectContext];
// . NSLog(#"get return managedObjectContext");
return _managedObjectContext;
}
- (NSManagedObjectContext *)getContextForBGTask {
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[context setParentContext:self.managedObjectContext];
return context;
}
- (NSArray*) allMapObj {
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* description =
[NSEntityDescription entityForName:#"MapObj"
inManagedObjectContext:self.managedObjectContext];
[request setEntity:description];
NSError* requestError = nil;
NSArray* resultArray = [self.managedObjectContext executeFetchRequest:request error:&requestError];
if (requestError) {
NSLog(#"%#", [requestError localizedDescription]);
}
return resultArray;
}
- (void)calculateDistanceWithCurrentLoaction:(CLLocation*) currentLoaction{
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSManagedObjectContext * bgcontext = [self getContextForBGTask];
NSEntityDescription* description =
[NSEntityDescription entityForName:#"MapObj"
inManagedObjectContext:bgcontext];
[request setEntity:description];
NSError* requestError = nil;
NSArray* resultArray = [bgcontext executeFetchRequest:request error:&requestError];
if (requestError) {
NSLog(#"%#", [requestError localizedDescription]);
}
for (MapObj *mapObject in resultArray) {
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:[mapObject.latitude doubleValue] longitude:[mapObject.longitude doubleValue]];
CLLocationDistance distance = [currentLoaction distanceFromLocation:endLocation];
mapObject.distance = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%f", distance]];
}
[bgcontext updatedObjects];
[self saveContextForBGTask:bgcontext];
}
- (void)saveContextForBGTask:(NSManagedObjectContext *)bgTaskContext {
if (bgTaskContext.hasChanges) {
[bgTaskContext performBlockAndWait:^{
NSError *error = nil;
[bgTaskContext save:&error];
}];
// Save default context
[self saveDefaultContext:YES];
}
}
- (void)saveDefaultContext:(BOOL)wait {
if (_managedObjectContext.hasChanges) {
[_managedObjectContext performBlockAndWait:^{
// . NSLog(#"managed context = %#", _managedObjectContext);
NSError *error = nil;
[self->_managedObjectContext save:&error];
}];
}
void (^saveMainPrivateManagedObjectContext) (void) = ^{
NSError *error = nil;
[self->_mainPrivateManagedObjectContext save:&error];
};
if ([_mainPrivateManagedObjectContext hasChanges]) {
if (wait){
// . NSLog(#"main context = %#", _mainPrivateManagedObjectContext);
[_mainPrivateManagedObjectContext performBlockAndWait:saveMainPrivateManagedObjectContext];
} else {
[_mainPrivateManagedObjectContext performBlock:saveMainPrivateManagedObjectContext];
}
}
}
Error in console:
2019-09-28 12:35:14.951873+0400 ProjectName[15695:4020487] *** Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore/UIKit-3698.140/UICollectionView.m:5972
CoreData: fault: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. attempt to perform an insert and a move to the same index path (<NSIndexPath: 0xa945f4d4afea737e> {length = 2, path = 0 - 4}) with userInfo (null)
What did I missed?
As a simple solution, was added:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
[self.collectionView performBatchUpdates:^{
......
if(self->_itemChanges.count > 1){
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
} else {
for (NSDictionary *change in self->_itemChanges) {
...
}
}
......
}

How to use CoreData in Xcode 8?

I am trying use CoreData, but when I add it to my project I only get two new methods :
- (NSPersistentContainer *)persistentContainer
and
- (void)saveContext
Now I can't get old methods to work with CoreData, and I can't find any tutorials with these new methods and Objective-C. How can I save and get data from CoreData using persistentContainer in Xcode 8 with Objective-c?
You can Get context as -
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
or as in Objective-C
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
And fetch data like -
var resultArray = try self.context.fetch(EntityName.fetchRequest())
or as in Objective-C
NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];
And fetch data with sorting -
var resultArray = [EntityName]()
do {
let request : NSFetchRequest<EntityName> = EntityName.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "somekey", ascending: true)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors
resultArray = try self.context.fetch(request)
} catch {
print("Error")
}
or as in Objective-C
NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"someKey" ascending:YES];
fetchRequest.sortDescriptors = #[sortDescriptor];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];
And add data like -
let entityNameObj = EntityName(context: context)
entityNameObj.title = "title"
or as in Objective-C
NSManagedObject *entityNameObj = [NSEntityDescription insertNewObjectForEntityForName:#"EntityName" inManagedObjectContext:context];
[entityNameObj setValue:#"someValue" forKey:#"someKey"];
And save context like -
do {
try self.context.save()
} catch _ as NSError {
print("Error")
}
or as in Objective-C
[((AppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
-(void)profileDatabase {
NSManagedObjectContext* context=[ADM.persistentContainer viewContext];
NSManagedObject *profile=[NSEntityDescription insertNewObjectForEntityForName:#"Profile" inManagedObjectContext:context];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"firstName"] forKey:#"firstName"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"surName"] forKey:#"surName"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"batchID"] forKey:#"batchID"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"profileImagePath"] forKey:#"profileImagePath"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"registeredEmail"] forKey:#"registeredEmail"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"role"] forKey:#"role"];
[profile setValue:[self.serverResponseOfProfileDict objectForKey:#"studentID"] forKey:#"studentID"];
NSLog(#"userObj:%#",profile);
NSError* error;
[context save:&error];
NSFetchRequest *fetchRequest=[[NSFetchRequest alloc]initWithEntityName:#"Profile"];
fetchRequest.returnsObjectsAsFaults=NO;
NSArray* results=[context executeFetchRequest:fetchRequest error:&error];
NSLog(#"Result:%#",results);
NSManagedObject *result=[results objectAtIndex:0];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"firstName"] forKey:#"firstName"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"surName"] forKey:#"surName"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"batchID"] forKey:#"batchID"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"profileImagePath"] forKey:#"profileImagePath"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"registeredEmail"] forKey:#"registeredEmail"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"role"] forKey:#"role"];
[ADM.databaseResponseOfProfileDict setObject:[result valueForKey:#"studentID"] forKey:#"studentID"];
NSLog(#"dic:%#",ADM.databaseResponseOfProfileDict);}
I have found a solution using Objective C. It runs, but I'm not sure that it is the correct solution.
- (void)dbManager {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, error.userInfo);
abort();
}
NSManagedObject *customAnimal = [NSEntityDescription insertNewObjectForEntityForName:#"Animals" inManagedObjectContext:context];
[customAnimal setValue:#"Lion" forKey:#"type"];
[customAnimal setValue:#"Rabit" forKey:#"name"];
[customAnimal setValue:#"Blue" forKey:#"color"];
[customAnimal setValue:#12 forKey:#"age"];
NSLog(#"Get data from DB");
NSMutableArray* animalsArray;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Animals"];
animalsArray = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(#"array is %#", animalsArray); // array is (
"<Animals: 0x6000000aee80> (entity: Animals; id: 0x60000022e120 <x-coredata:///Animals/tAAC7332D-6BEF-441C-9041-0ECB57469FA62> ; data: {\n age = 12;\n color = Blue;\n name = Rabit;\n type = Lion;\n})"
}
For all the beginners out there, this will give you the basic idea.
welcome.m
==========
#import "welcomepage.h"
#import "Register.h"
#import "login.h"
#import "AppDelegate.h"
#import "Student+CoreDataProperties.h"
#import "loginbtn.h"
#import "King+CoreDataProperties.h"
#interface welcomepage ()
{
AppDelegate *a;
NSManagedObjectContext *context;
}
#end
#implementation welcomepage
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (IBAction)login:(id)sender
{
loginbtn *lb=[[loginbtn alloc]init];
[self.navigationController pushViewController:lb animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)register:(id)sender
{
a=(AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context1=((AppDelegate *)[UIApplication sharedApplication].delegate).persistentContainer.viewContext;
Student *ss=[NSEntityDescription insertNewObjectForEntityForName:#"Student" inManagedObjectContext:context1];
ss.name=[NSString stringWithFormat:#"%#",_txtfld1.text];
ss.age=[NSString stringWithFormat:#"%#",_txtfld2.text];
ss.place=[NSString stringWithFormat:#"%#",_txtfld3.text];
[a saveContext];
if (_txtfld1.text.length && _txtfld2.text.length && _txtfld3.text.length != 0)
{
UIAlertView *al=[[UIAlertView alloc]initWithTitle:#"THANK YOU" message:#"DATA SUCESSFULLY SAVER. YOU CAN LOGIN NOW WITH YOUR PASSWORD AND NAME" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[al show];
_txtfld1.text=#"";
_txtfld2.text=#"";
_txtfld3.text=#"";
Register *rg=[[Register alloc]init];
[self.navigationController pushViewController:rg animated:YES];
}
else
{
UIAlertView *al2=[[UIAlertView alloc]initWithTitle:#"WARRNING" message:#"PLEASE FILL THE DATA COMPLETELY" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[al2 show];
}
}
===================================================
Register.m
==========
#import "Register.h"
#import "AppDelegate.h"
#import "Student+CoreDataProperties.h"
#import "welcomepage.h"
#interface Register ()<UITableViewDelegate,UITableViewDataSource>
{
AppDelegate *a;
NSManagedObjectContext *context01;
NSArray *array01;
}
#end
#implementation Register
- (void)viewDidLoad
{
[super viewDidLoad];
a=((AppDelegate *)[UIApplication sharedApplication].delegate);
context01=((AppDelegate *)[UIApplication sharedApplication].delegate).persistentContainer.viewContext;
// specifying nsrequest and nsentity
NSFetchRequest *req=[[NSFetchRequest alloc]init];
NSEntityDescription *entity01=[NSEntityDescription entityForName:#"Student" inManagedObjectContext:context01];
[req setEntity:entity01];
// putting datas from reto array
NSError *err=nil;
array01=[context01 executeFetchRequest:req error:&err];
// Do any additional setup after loading the view from its nib.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return array01.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ci=#"hai";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ci];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ci];
}
if (indexPath.row==0) {
cell.textLabel.text=[[array01 objectAtIndex:indexPath.section]valueForKey:#"name"];
}
if (indexPath.row==1) {
cell.textLabel.text=[[array01 objectAtIndex:indexPath.section]valueForKey:#"age"];
}
if (indexPath.row==2) {
cell.textLabel.text=[[array01 objectAtIndex:indexPath.section]valueForKey:#"place"];
}
return cell;
}
==================================================
Loginbtn.m
============
#import "loginbtn.h"
#import "AppDelegate.h"
#import "Student+CoreDataProperties.h"
#import "login.h"
#interface loginbtn ()
{
AppDelegate *a;
NSArray *arraylb;
}
#end
#implementation loginbtn
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)lgbtn:(id)sender
{
a=(AppDelegate *)[UIApplication sharedApplication].delegate;
//xcode 8.2.1 specification code
NSManagedObjectContext *context=((AppDelegate *)[UIApplication sharedApplication].delegate).persistentContainer.viewContext;
//creating feathch request and entity
NSFetchRequest *req=[[NSFetchRequest alloc]init];
NSEntityDescription *entity=[NSEntityDescription entityForName:#"Student" inManagedObjectContext:context];
[req setEntity:entity];
// setting predicate
NSPredicate *pre=[NSPredicate predicateWithFormat:#"age like %# and place like %#",_txt1.text,_txt2.text];
[req setPredicate:pre];
//creating error and array to store
NSError *err=nil;
arraylb=[[NSArray alloc]init];
arraylb=[context executeFetchRequest:req error:&err];
login *lg=[[login alloc]init];
if (arraylb.count!=0)
{
lg.array001=arraylb;
}
//
// if (arraylb.count!=0)
//// {
////
//// lv *lvi=[[lv alloc]init];
////
//// //passing value
//// lvi.array001=arraylb;
////
////
//// //lv.str1=self.tf1.text;
//// //lv.str2=self.tf2.text;
//// [self.navigationController pushViewController:lvi animated:YES];
////
////
//// }
//// else
//// {
//
// self.lb.text=#"Invalid username & password";
//
// }
//
[self.navigationController pushViewController:lg animated:YES];
}
=====================================================
Lohin.m
=========
#import "login.h"
#import "Student+CoreDataProperties.h"
#import "AppDelegate.h"
#import "loginbtn.h"
#interface login ()
{
AppDelegate *a;
NSArray *array01;
}
#end
#implementation login
- (void)viewDidLoad
{
[super viewDidLoad];
_txt11.text=[[_array001 objectAtIndex:0]valueForKey:#"name"];
_txt22.text=[[_array001 objectAtIndex:0]valueForKey:#"age"];
_txt33.text=[[_array001 objectAtIndex:0]valueForKey:#"place"];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
// Dispose of any resources that can be recreated.
}

CoreData - could not locate an NSManagedObjectModel

I'm getting the error below, I don't know what I'm doing wrong.
I guess there is the managedobject which cannot be located, but... arf !
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Boxes''
here is my .m ( only the two main functions )
- (void)loadCoreData
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test" object:self];
context = [app managedObjectContext];
NSError *err;
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
}
- (void) fillSexArray:(NSString *)sexe
{
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
NSPredicate *sex;
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
// NSUInteger numObjects = [mutableArray count];
}
my .h :
#interface AddViewController : UIViewController
{
IBOutlet UIButton *male;
IBOutlet UIButton *female;
IBOutlet UIButton *couple;
UIButton *maleBtn;
BOOL flag;
NSArray *arrayForPredicate;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *context;
NSFetchRequest *request;
}
#property (nonatomic, retain) WonderAppDelegate *app;
- (void) fillSexArray:(NSString *)sexe;
- (NSMutableArray *)createMutableArray:(NSArray *)array;
- (void)loadCoreData;
- (void)sexeButtonPressed;
- (void)sexeArray;
#end
EDIT creating the managedObject :
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes"
inManagedObjectContext:managedObjectContext];
boxes.name = [dict objectForKey:#"name"];
boxes.sexe = [dict objectForKey:#"sexe"];
boxes.topic = [dict objectForKey:#"topic"];
boxes.number = [dict objectForKey:#"number"];
return boxes;
}
This is my .m and it is working like that but i don't want the code of the function Add there i want it on loadCoreData.
//
// AddViewController.m
// CoreDataTuto
//
// Created by Clement Yerochewski on 30/04/12.
// Copyright (c) 2012 Weblib. All rights reserved.
//
#import "AddViewController.h"
#import "Boxes.h"
#implementation AddViewController
#synthesize app, context;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:#"Add Detail"];
[navBar pushNavigationItem:navItem animated:NO];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(cancel)];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Add" style:UIBarButtonItemStyleBordered target:self action:#selector(add)];
navItem.leftBarButtonItem = cancelButton;
navItem.rightBarButtonItem = addButton;
[self.view addSubview:navBar];
app = [[UIApplication sharedApplication] delegate];
}
return self;
}
- (void) add{
[self dismissModalViewControllerAnimated:YES];
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH A LENGTH NAME <= 5
// NSPredicate *length;
// length = [NSPredicate predicateWithFormat:#"name.length <= 5"];
// NSArray *BoxWithCheapPrice = [array filteredArrayUsingPredicate:length];
// NSLog(#"Box %#", BoxWithCheapPrice);
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH PRICE BETWEEN $MIN AND $MAX
// NSNumber *min = [NSNumber numberWithInteger:30];
// NSNumber *max = [NSNumber numberWithInteger:100];
// NSPredicate *between;
// between = [NSPredicate predicateWithFormat:#"number BETWEEN %#", [NSArray arrayWithObjects:min, max, nil]];
// NSArray *BoxWithPriceBetween = [array filteredArrayUsingPredicate:between];
// NSLog(#"Box %#", BoxWithPriceBetween);
// NSLog(#"%#", [BoxWithPriceBetween valueForKey:#"name"]);
}
- (NSMutableArray *)createMutableArray:(NSArray *)array
{
return [NSMutableArray arrayWithArray:array];
}
- (IBAction) sexeChoosen: (id) sender
{
switch ( ((UIButton*)sender).tag ){
case 0:
[self fillSexArray:#"male"];
break;
case 1:
[self fillSexArray:#"female"];
break;
default:
[self fillSexArray:#"both"];
}
[self sexeButtonPressed];
}
- (void)sexeButtonPressed
{
if (flag)
{
UIImage * maleImg2 = [UIImage imageNamed:#"pressed.png"];
[maleBtn setImage:maleImg2 forState:UIControlStateNormal];
flag = NO;
[self sexeArray];
}
else
{
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
flag = YES;
[self sexeArray];
}
}
- (void)sexeArray
{
}
- (void)loadCoreData
{
}
- (void) fillSexArray:(NSString *)sexe
{
context = [app managedObjectContext];
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError *err;
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
NSPredicate *sex;
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
NSLog(#"SEXE CHOOSEN %#", mutableArray);
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
NSUInteger numObjects = [mutableArray count];
NSLog(#"%d", numObjects);
}
- (void) cancel{
[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
flag = YES;
maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maleBtn.frame = CGRectMake(40, 47, 107, 75);
[maleBtn setTitle:#"male" forState:UIControlStateNormal];
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
[maleBtn addTarget:self action:#selector(sexeChoosen:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:maleBtn];
[self loadCoreData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Have you updated your model after creating the persistent store? Try to delete your app from the simulator (or the database file) and run it again..

NSArray causes EXC_BAD_ACCESS

I declare an NSArray in one class like this:
.h
#interface HTTP : NSObject {
NSArray *listOfProfiles;
}
#property (nonatomic, retain) NSArray *listOfProfiles;
.m
-(id) init {
if ((self = [super init])) {
listOfProfiles = [[NSArray alloc] init];
}
return self;
}
-(void) someMethod {
...
case GET_LIST_OF_PROFILES:
listOfProfiles = [result componentsSeparatedByString:#"^-^"];
NSLog(#"first break: %#",[listOfProfiles objectAtIndex:0]);
break;
...
}
I can access it here just fine, then when I try to access it in another class after creating an object I receive the error EXC_BAD_ACCESS and the debugger goes to main.m:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
http = [[HTTP alloc] init];
[http createProfileArray];
profileListDelay = [[NSTimer alloc] init];
profileListDelay = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(profileListSelector) userInfo:nil repeats:YES];
}
- (void) profileListSelector
{
if (http.activityDone)
{
// http.listofprofiles mem leak?
for (int i = 0; i < http.listOfProfiles.count; i++)
{
NSLog(#"%#",[http.listOfProfiles objectAtIndex:i]);
}
[profileListDelay invalidate];
profileListDelay = nil;
}
}
I'm thinking it's a memory issue maybe, but I could be completely wrong.
It is a memory issue
It is in someMethod
-(void) someMethod {
...
case GET_LIST_OF_PROFILES:
listOfProfiles = [result componentsSeparatedByString:#"^-^"];
NSLog(#"first break: %#",[listOfProfiles objectAtIndex:0]);
break;
...
}
componentsSeparatedByString: returns an autoreleased object
Since you declared the array as a retain property, you should update it like so:
self.listOfProfiles = [result componentsSeparatedByString:#"^-^"];

managedObjectContext save issue

Over the last few days, I've searched far and wide and followed every resolution I could find online with no success.
Basically, I'm refreshing a Core Data entity from JSON data I pull from the web. I can clear out the previous data pulled from the web and load in the new data. The problem occurs when I attempt to save to Core Data "[self.managedObjectContext save:&error];".
The app just locks up.
The code from my view controller is shown below. I would greatly appreciate any assistance.
** CODE ***
//
// ChargeEntryViewController.m
// pcc
//
// Created by Tim Black on 3/14/11.
// Copyright 2011 Mobile Intents. All rights reserved.
//
#import "ChargeEntryViewController.h"
#import "pccAppDelegate.h"
#import "ChargeEntryPatientViewController.h"
#import "CJSONDeserializer.h"
#interface ChargeEntryViewController (PrivateMethods)
- (NSString *)jsonFromURLString:(NSString *)urlString;
- (void)handleError:(NSError *)error;
#end
#implementation ChargeEntryViewController
#synthesize fetchedResultsController=fetchedResultsController_;
#synthesize managedObjectContext=managedObjectContext_;
#synthesize providerArray;
#synthesize clearBtn;
#synthesize setBtn;
#synthesize patientController;
#pragma mark - Button methods
-(IBAction) clearAll:(id)sender{
selRow = -1;
[providerList reloadData];
}
-(IBAction) setPatientView:(id)sender {
if (self.patientController == nil) {
ChargeEntryPatientViewController *tmpController = [[ChargeEntryPatientViewController alloc] initWithNibName:#"ChargeEntryPatientView" bundle:nil];
self.patientController = tmpController;
[tmpController release];
}
patientController.title = #"Patient Selection";
[self.navigationController pushViewController:patientController animated:YES];
}
/*
Used to refresh the providers list from nrhsportal
*/
-(void)refreshProviders {
NSError *error = nil;
// get provider code from app delegate
pccAppDelegate *appDelegate = (pccAppDelegate *)[[UIApplication sharedApplication] delegate];
// first, clear out current list stored locally
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:#"Provider" inManagedObjectContext:self.managedObjectContext]];
NSArray *result = [self.managedObjectContext executeFetchRequest:fetch error:&error];
if (error != nil) {
[self handleError:error];
return;
}
for (id basket in result) {
[self.managedObjectContext deleteObject:basket];
}
// add (My Patients) entry
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
[newManagedObject setValue:#"(My Patients)" forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
NSString *code = appDelegate.groupCode;
// create remote source URI
NSString *urlString = [NSString stringWithFormat:#"%s%#%s", "https://nrhsportal.nrh-ok.com/pccdata.svc/GetProviders?groupcode='", code, "'&$format=json"];
NSLog(#"URL String %#", urlString);
// Perform HTTP GET to the REST web service which returns JSON
NSString *jsonString = [self jsonFromURLString:urlString];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
// Parse JSON results to convert to a dictionary
CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
error = nil;
NSDictionary *resultsDictionary = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];
if (error != nil) {
[self handleError:error];
return;
}
// Traverse through returned dictionary to populate tweets model
NSDictionary *topArray = [resultsDictionary objectForKey:#"d"];
NSArray *resultsArray = [topArray objectForKey:#"results"];
for (NSDictionary *resultDictionary in resultsArray) {
// create the
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
NSString *providerName = [resultDictionary objectForKey:#"fullname"];
[newManagedObject setValue:providerName forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
}
error = nil;
[self.managedObjectContext save:&error];
if (error != nil) {
[self handleError:error];
return;
}
[newManagedObject release];
[result release];
}
// This will issue a request to a web service API via HTTP GET to the URL specified by urlString.
// It will return the JSON string returned from the HTTP GET.
- (NSString *)jsonFromURLString:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[request release];
[self handleError:error];
NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return [resultString autorelease];
}
// This shows the error to the user in an alert.
- (void)handleError:(NSError *)error {
if (error != nil) {
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[errorAlertView show];
[errorAlertView release];
}
}
#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
selRow = -1;
// refresh the provider list from remote data
[self refreshProviders];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:#"fullname"] description];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
if ([cell.textLabel.text isEqualToString: #"(My Patients)"]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
}
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"fullname" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController_;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[patientController release];
[clearBtn release];
[setBtn release];
[providerArray release];
[fetchedResultsController_ release];
[managedObjectContext_ release];
[super dealloc];
}
#end
You don't need the line
[self.managedObjectContext insertObject:newManagedObject];
since you've already insertNewObjectForEntityForName before with the newManagedObject.