Since I get into a requirement of saving NSDictionary offline and populate the table from it when the user is offline.
This is the code I have so far:
Everytime the resulting NSDictionary was getting as nil
I have made this attribute set as transformable
+ (void) insertIntoCoredata :(NSString *) table : (NSString *) attribute : (NSArray *) dic {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dic];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:table
inManagedObjectContext:context];
[object setValue:myData forKey:attribute];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
}
+ (id) getFromCoredata :(NSString *) table : (NSString *) attribute {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:table
inManagedObjectContext:context];
[fetch setEntity:entityDescription];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}
What went wrong with this code.
Related
I fetched the objects in an core data entity. Then I cross check with a NSArray and find out what are the existing objects in the data base.
Then I insert new objects to database. I am struggling in how to update existing objects in this code. Please help me to do it in best way.
// get manageObjectContext
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSArray *arrIds = [arr valueForKeyPath:#"anId"];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"SomeEntity"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"%K IN %#", #"anId", arrIds];
NSArray *existingItems = [context executeFetchRequest:fetchRequest error:&error];
//Get the existing ids:
NSArray *existingIds = [existingItems valueForKeyPath:#"anId"];
for (NSDictionary *item in arr) {
if ([existingItems containsObject:topic[#"anId"]]) {
// update exsising item
}
else{
// Insert new items done .........
}
you can use this code!!
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Qr_code"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(user_ID=%#)",
kText];
[request setPredicate:pred];
matches = nil;
NSError *error;
updatedata = [context executeFetchRequest:request
error:&error];
if ([updatedata count] == 0) {
} else {
matches=updatedata[0];
}
I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}
I'am getting
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject persistentStore]: unrecognized selector sent to instance 0x3bebf50'
and
while loading data from core data.I have referred links iOS Persistent store issue but it didnt solved my issue. Also data not saving to tableview.
Earlier it was loading but due to large data I've used background core data saving. but for now No data loading from DB. I'm using NSFetchResultController for fetching data.
-(void)updateThreadEntityWithSyncDetails:(NSMutableDictionary *)inDictionary
{
dispatch_queue_t backgroundQueue = dispatch_queue_create("backgroundQueueName", NULL);
NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:#"currentUser"];
AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSManagedObjectContext *contextforThread = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
contextforThread.parentContext = context;
[contextforThread performBlock:^{
// AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"ThreadInfo"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:#"userEmail == %#",loginUser];
NSPredicate *threadPredicate = [NSPredicate predicateWithFormat:#"threadID == %#",[inDictionary valueForKey:#"thread"]];
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: #[userPredicate, threadPredicate]];
[fetchRequest setPredicate:compoundPredicate];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:nil];
for (ThreadInfo *threadInfo in fetchedObjects)
{
if([[inDictionary allKeys] containsObject:#"userEmail"])
{
if([inDictionary valueForKey:#"userEmail"]!=[NSNull null])
{
threadInfo.userEmail=[inDictionary valueForKey:#"userEmail"];
}
}
if([[inDictionary allKeys] containsObject:#"secret_seed"])
{
if([inDictionary valueForKey:#"secret_seed"]!=[NSNull null])
{
threadInfo.threadSecret=[NSString stringWithFormat:#"%#",[inDictionary valueForKey:#"secret_seed"]];
}
}
if([[inDictionary allKeys] containsObject:#"r_key"])
{
if([inDictionary valueForKey:#"r_key"]!=[NSNull null])
{
threadInfo.remoteKey=[inDictionary valueForKey:#"r_key"];
}
}
if([[inDictionary allKeys] containsObject:#"solicitation"])
{
if([inDictionary valueForKey:#"solicitation"]!=[NSNull null])
{
threadInfo.solicitationID=[inDictionary valueForKey:#"solicitation"];
}
}
if([[inDictionary allKeys] containsObject:#"r_secret"])
{
if([inDictionary valueForKey:#"r_secret"]!=[NSNull null])
{
threadInfo.remoteSecret=[inDictionary valueForKey:#"r_secret"];
}
}
NSError *error;
if (![contextforThread save:&error]) {
NSLog(#"Could not insert to userInfo: %#", [error localizedDescription]);
}
[context performBlock:^{
NSError *error;
if (![context save:&error]) {
NSLog(#"Could not insert to userInfo: %#", [error localizedDescription]);
}
}];
}];
// if (![context save:&error]) {
// NSLog(#"Could not update to threadInfo: %#", [error localizedDescription]);
// }
}
Appdelegate
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
// _managedObjectContext = [[NSManagedObjectContext alloc] init];
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"IXCoreDataModel" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Inxed.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
FetchedResultsController
-(NSFetchedResultsController*)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:#"currentUser"];
AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"ThreadInfo"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:#"threadDate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSPredicate *threadPredicate = [NSPredicate predicateWithFormat:#"userEmail == %#",loginUser];
// NSPredicate *providerPredicate = [NSPredicate predicateWithFormat:#"isReceiver == YES"];
// NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: #[threadPredicate, providerPredicate]];
[fetchRequest setPredicate:threadPredicate];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context sectionNameKeyPath:nil
cacheName:nil];
_fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
CRASH CODE
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
ThreadInfo *info=[_fetchedResultsController objectAtIndexPath:indexPath];
if([info.isSystemMessage boolValue])// CRASH CoreData: error: NULL _cd_rawData but the object is not being turned into a fault
{
return 178+90+25;
} else {
return 178;
}
getting
CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Only run on the main thread! with userInfo (null)
When scrolling to last cell, I'm getting this crash too with nothing in the cell.
Make sure you save your contexts in performBlock method like
[mainContext performBlock^{
[mainContext save:&error];
}];
Also refer this thread
I am using this piece of code to find the existance of data. But i am getting this error that Use of Undeclared Identifier "appDelegate".
- (IBAction)findContact:(id)sender {
CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Contacts"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(name = %#)",
_name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request
error:&error];
if ([objects count] == 0) {
_status.text = #"No matches";
} else {
matches = objects[0];
_address.text = [matches valueForKey:#"address"];
_phone.text = [matches valueForKey:#"phone"];
_status.text = [NSString stringWithFormat:
#"%lu matches found", (unsigned long)[objects count]];
}
}
I have included the #import <CoreData/CoreData.h> .Will I have to include some other file. When i save data it works fine.
Ensure you have imported the app delegate header
#import "CoreDataAppDelegate.h"
Try casting the AppDelegate as CoreDataAppDeleage
CoreDataAppDelegate *appDelegate = (CoreDataAppDelegate*)[[UIApplication sharedApplication] delegate];
CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
Replace above line to below line
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
For deleting text based on Id
#pragma mark - delete tracking details
- (void)deleteTrackingId:(NSString *)trackingId
{
appDelegate = [[UIApplication sharedApplication] delegate];
managedObjectContext = appDelegate.managedObjectContext;
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityOne = [NSEntityDescription entityForName:#"TrackingList" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entityOne];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"trackingId == %#",trackingId];
[fetchRequest setPredicate:predicate];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(#"Could not delete Entity Objects");
}
for (TrackingList *trackingObject in fetchedObjects) {
[managedObjectContext deleteObject:trackingObject];
}
[appDelegate saveContext];
}
I have save a NSARRAY in my nscoredatabase in binarydata type attribute saved with this code
AppDelegate *AppDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[AppDelegate managedObjectContext];
//guardar array
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:roll];
NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:#"Horarios"
inManagedObjectContext:context];
[newContact setValue:arrayData forKey:#"valor"];
NSError *error;
[context save:&error];
But i dont know how to get it back from the data store to work again with this NSARRAY
Someone can help me?
Try this code:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Horarios"];
NSError *error;
NSArray *matches = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Solved adding this line
[fetchRequest setReturnsObjectsAsFaults:NO];