I am new to Core Data, and I am trying to use it for saving users. However, when I first create a user it inserts the user. This seems to go fine. It is only called once.
-(void)insertUser: (User *) user{
[self userToModel:user];
NSError *error = nil;
if(![context save:&error]){
NSLog(#"Unable to save managed object context");
}
}
-(UserModel *)userToModel:(User *) user{
UserModel *usermodel = [NSEntityDescription
insertNewObjectForEntityForName:#"UserModel"
inManagedObjectContext:context];
[usermodel setValue:user.username forKey:#"username"];
[usermodel setValue:user.password forKey:#"password"];
[usermodel setValue:user.sessionid forKey:#"sessionid"];
[usermodel setValue:[NSNumber numberWithBool:TRUE] forKey:#"selected"];
[usermodel setValue:[NSNumber numberWithBool:user.beta] forKey:#"beta"];
return usermodel;
}
Next, I am fetching the users and it is returning 3 users: 2 exact similar Users, and one nil model.
-(NSMutableArray *)getUsers{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"UserModel"
inManagedObjectContext:context];
NSError *error;
[fetchRequest setEntity:entity];
NSArray *usermodels= [context executeFetchRequest:fetchRequest error:&error];
NSMutableArray *users = [[NSMutableArray alloc] init];
for(UserModel *userModel in usermodels){
User *user = [self userModelToUser:userModel];
[users addObject:user];
}
return users;
}
UserModelToUser:
-(User *)userModelToUser:(UserModel *)usermodel{
User *user = [[User alloc]initWithUsername:usermodel.username
Password:usermodel.password
CSRFToken:usermodel.csrftoken
sessionid:usermodel.sessionid
Beta:[usermodel.beta boolValue]
Selected:[usermodel.selected boolValue]];
return user;
}
SelectUser
-(void)selectUser: (User *)userToSelect OldUser:(User *)oldSelectedUser{
UserModel *oldSelectedUserModel = [self userToModel:oldSelectedUser];
UserModel *newSelectedUsermodel = [self userToModel:userToSelect];
[oldSelectedUserModel setValue:[NSNumber numberWithBool:FALSE] forKey:#"selected"];
[newSelectedUsermodel setValue:[NSNumber numberWithBool:TRUE] forKey:#"selected"];
NSError *saveError;
if (![context save:&saveError]) {
NSLog(#"Changing users failed %#", saveError);
}
}
I already tried to reinstall the app to make sure no old users are still saved or anything. Can anyone help me?
Related
I am getting only last record from coredata? below is the my code .
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company"
inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
[object setValue:#"wipro" forKey:#"cname"];
[object setValue:#"02" forKey:#"compID"];
[object setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
}
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
Add objects like this,
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
NSManagedObject *object2 = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object2 setValue:#"wipro" forKey:#"cname"];
[object2 setValue:#"02" forKey:#"compID"];
[object2 setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
}
i am new to core data..
I know how to store and item.
- (void)dbSave:(NSString *)uri withContent:(NSDictionary *)content withExpiry:(double)date {
Cache *cache = [self dbLoad:uri];
if (cache == nil) {
cache = [NSEntityDescription insertNewObjectForEntityForName:#"Cache" inManagedObjectContext:[self managedObjectContext]];
}
double time = (double) [[NSDate date] timeIntervalSince1970] + date;
[cache setLocal:uri];
[cache setTime:#(time)];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:content forKey:#"data"];
[archiver finishEncoding];
[cache setData:data];
NSError *error;
if (![[self managedObjectContext] save:&error]) {
}
}
But i am stuck with creating a method to clear this core data data base.. Does anyone know how?
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:#"entity"];
NSArray* currentRecord = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (currentRecord.count)
{
for (NSManagedObject *obj in currentRecord)
{
[managedObjectContext deleteObject:obj];
}
NSError * error = nil;
if (![managedObjectContext save:&error])
NSLog(#"Can't save ! %# %#",error,[error localizedDescription]);
else
NSLog(#"Data deleted");
}
use this
NSManagedObjectContext *managedContext = [[APP_DELEGATE dbManagerObj] newPrivateContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Cache"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isUserData = %#",[NSNumber numberWithBool:true]];
[fetchRequest setPredicate:predicate];
if (IS_IOS9_ANDABOVE) {
NSBatchDeleteRequest *batchDeleteRequest = [[NSBatchDeleteRequest alloc]initWithFetchRequest:fetchRequest];
[[[APP_DELEGATE dbManagerObj]persistentStoreCoordinator]executeRequest:batchDeleteRequest withContext:managedContext error:nil];
}
else
{
NSArray *userRelatedDay = [managedContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in userRelatedDay) {
[managedContext deleteObject:object];
}
}
I am new in iOS and I am facing a problem regarding to update value of coredata.
For Save
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *device;
if (self.device) {
// Update existing device
[device setValue:GlobalIndexPath forKey:#"key"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Device" inManagedObjectContext:context];
[newDevice setValue:GlobalIndexPath forKey:#"key"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
My code to fetch core data is
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"EntityName" inManagedObjectContext:context]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
And to update I and using code
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
Update code not update it add one object.
Note - GlobalIndexPath is a name of string.
But this is not working for me any suggestion. Thanks in Advcance!
You need to save the context every time you make changes to any NSManagedObject and want it to persist. Try this:
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
I am trying to store product in sqlite. When i setValue for database entity then i store correct value.
But problem is that i make a check if product is already in database then it should not add same product again. But next time it store NULL value in database.
Although i am not calling [addToFav setValue:#"My Value"];
Simply its check in for loop. When my loop runs it won't go in first condition where i make counter if(count == 0)
I don't know where from its storing NULL value. While i am not calling it any where else. So how its storing NULL value in database ?
- (IBAction)buttonAddToFavourite:(id)sender {
int count = 0;
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSManagedObject *addToFav = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:context];
NSString *dish = [results objectForKey:#"id"];
fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Favourite" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSString *id1 = [info valueForKey:#"dishid"];
if ([id1 isEqualToString:dish]) {
count = count +1;
}
}
if (count == 0) {
[addToFav setValue:[results objectForKey:#"id"] forKey:#"dishid"];
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else if (count > 0){
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
- (IBAction)buttonAddToFavourite:(id)sender {
NSError *error = nil;
NSString *dishId = results[#"id"];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Favourite"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"dishid == %#", dishId]];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count) {
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else {
Favourite *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:self.managedObjectContext];
obj.dishid = dishId;
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
I have an array friendsArray of dictionary objects which looks something like this:
(
{
name = "james p";
phone = 345345345;
},
{
name = "sam b";
phone = 345345345;
},
{
name = "aaron s";
phone = 346346456;
}
)
Now I'm storing it to coredata like this
NSMutableDictionary *friends = [[NSMutableDictionary alloc] init];
for (int count = 0; count <[friendsArray count]; count++) {
NSError *error;
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"FriendContacts" inManagedObjectContext:context];
NSManagedObject *friendsObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
friends = [friendsArray objectAtIndex:count];
[friendsObject setValue:[friends objectForKey:#"name"] forKey:#"name"];
[friendsObject setValue:[friends objectForKey:#"phone"] forKey:#"phone"];
[context save:&error];
}
Here is the screenshot of SQL Browser
It is storing data but making duplicate of this dictionary, I don't know why.
Try the following - its a bit cleaner :)
Observe how many times the log statement is outputted and check the object it outputs.
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"FriendContacts" inManagedObjectContext:context];
for (NSDictionary *friend in friendsArray) {
NSManagedObject *friendsObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];
[friendsObject setValue:[friend objectForKey:#"name"] forKey:#"name"];
[friendsObject setValue:[friend objectForKey:#"phone"] forKey:#"phone"];
NSLog(#"Created new friends object: %#", friendsObject);
if ([context hasChanges]) {
NSError *error;
if (![context save:&error]) {
NSLog(#"Problem saving changes: %#", error);
}
}
}
EDIT:
You might also be better off saving after the loop is finished too (if you have a large data set), just move the if statement outside the loop.