I'm making the app using core-data.
It's facebook app, so I saved the User information to core-data.
And I wanna add the profile picture to user information data.
for (UserInfo *info in fetchedObjects) {
if ([info.fbId isEqualToString:delegate.currentUserInfo.fbId]) {
info.details.photos.image = [NSData dataWithContentsOfURL:url];
info.details.photos.imageId = [result objectForKey:#"id"];
info.details.photos.details = info.details;
delegate.currentUserInfo = info;
for (UserInfo *info in fetchedObjects) {
NSLog(#"currentUserInfo : %#", info);
NSLog(#"curretnUserDetails : %#", info.details);
NSLog(#"currentUserPhoto : %#", info.details.photos);
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
}
Like this, I add the data to the core-data (relationshop named photos) corresponding to FB user ID.
As a result, NSLog in the middle shows well photoInfo data, but when I restart my app, there is no photo data.
I didn't solve this problem for a few days. Help me!
-edited
DataModel is organized like this picture.
I'm using only one context, and I'm novice so I can't understand all of thankful comment.
-edited2
if (!beExist) {
UserInfo *userInfo = [NSEntityDescription insertNewObjectForEntityForName:#"UserInfo" inManagedObjectContext:context];
userInfo.name = [myInfoDic objectForKey:#"name"];
userInfo.fbId = [myInfoDic objectForKey:#"id"];
userInfo.type = #"user";
UserDetails *userDetails = [NSEntityDescription insertNewObjectForEntityForName:#"UserDetails" inManagedObjectContext:context];
userDetails.gender = [myInfoDic objectForKey:#"gender"];
userDetails.work = [[[[myInfoDic objectForKey:#"work"] objectAtIndex:0] objectForKey:#"employer"] objectForKey:#"name"];
NSArray *eduArray = [myInfoDic objectForKey:#"education"];
userDetails.education = [[[eduArray objectAtIndex:eduArray.count-1] objectForKey:#"school"] objectForKey:#"name"];
userDetails.birthday = [myInfoDic objectForKey:#"birthday"];
userDetails.location = [[myInfoDic objectForKey:#"location"] objectForKey:#"name"];
PhotoInfo *photoInfo = [NSEntityDescription insertNewObjectForEntityForName:#"PhotoInfo" inManagedObjectContext:context];
userDetails.info = userInfo;
userInfo.details = userDetails;
userInfo.details.photos = photoInfo;
photoInfo.details = userDetails;
delegate.currentUserInfo = userInfo;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
I saved User information like this.
I created context in AppDelegate. I made the project for Core data, so Xcode made that code.
I can see this log
2012-05-04 00:40:58.997 Feek[16423:fb03] currentUserPhoto : <PhotoInfo: 0x6d15d60> (entity: PhotoInfo; id: 0x6d18550 <x-coredata://2ED200FE-D799-4C66-A0AC-5BE1BC426439/PhotoInfo/p1> ; data: {
details = "0x8830ca0 <x-coredata://2ED200FE-D799-4C66-A0AC-5BE1BC426439/UserDetails/p1>";
image = <ffd8ffe0 00104a46 49460001 02000001 00010000 fffe0004 2a00ffe2 021c4943 435f5052 4f46494c 45000101 0000020c 6c63>;
imageId = 334168116641714;
})
I think that this is core data accept data, but it doesn't remain after killing my app.
Related
i will try to work with multiple entity with core data.
core data in two entity name is Student and Detail both have inverse relationship. relationship name is Student -> Detail:detail Detail -> Student:student.
try to fetch record from both entity and display in table view. try multiple code but can't get result.
first code:
Detail *d;
NSMutableArray *arrObj = [[NSMutableArray alloc]init];
for(Student *tblObj in [d student]){
[arrObj addObject:tblObj];
}
NSLog(#"Your records related with tableA = %#",arrObj);
can't load data in array.
second code:
NSArray* fetchResults = [_mainContext executeFetchRequest:fetchRequest error:nil];
for (int i; i > 1; i++) {
Student *tableAObject = fetchResults[i];
NSString * itemcode = tableAObject.detail.email;
NSLog(#"%#",itemcode);
}
can't display record.
third way:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *aEntity = [NSEntityDescription entityForName:#"Student" inManagedObjectContext:_mainContext];
[fetchRequest setEntity:aEntity];
NSString *relationshipKeyPath = #"detail"; // Set this to the name of the relationship on "SP" that points to the "Code" objects;
NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
[fetchRequest setRelationshipKeyPathsForPrefetching:keyPaths];
NSMutableArray *arrObj = [[NSMutableArray alloc]init];
for(Student *spObj in arrObj)
{
NSLog(#"description is %#",spObj.name);
Detail *codObj = spObj.detail;
NSLog(#"it has value %#",codObj);
NSLog(#" unique name is %#",codObj.email);
}
Code for insert data in core dta:
- (IBAction)submitData:(id)sender {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate manageObjectContext];
Student *student = (Student *)[NSEntityDescription insertNewObjectForEntityForName:#"Student" inManagedObjectContext:context];
student.name = _nameText.text;
student.number = _noText.text;
student.study = _studyText.text;
Detail *detail = (Detail *)[NSEntityDescription insertNewObjectForEntityForName:#"Detail" inManagedObjectContext:context];
detail.number = _noText.text;
detail.email = _emailText.text;
detail.address = _addressText.text;
detail.contact = _contactText.text;
student.detail = detail;
detail.student = student;
NSError *error = nil;
[context save:&error];
if (![context save:&error]) {
NSLog(#"error in adding data %#, %#", error, [error userInfo]);
abort();
}
}
if you need more details let me know. Thank you.
The first two ways you have tried won't work as there is no code that related to fetch the data from core data. In the third way problem is you are not executing your fetch request.
Following is the way to fetch data from core data.
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:#"Student"];
NSError *error = nil;
NSArray *students = [context executeFetchRequest:req error:&error];
for (Student *stdObj in students)
{
//Student object
NSLog(#"Name %#",stdObj.name);
NSLog(#"Number %#",stdObj.number);
//Detail object related to student
Detail *detailObj = stdObj.detail;
NSLog(#"Email %#",detailObj.email);
NSLog(#"Address %#",detailObj.address);
}
I have one array list like this:
(
"08-12-2016, Thursday, Greg",
"15-12-2016, Thursday, Greg",
"22-12-2016, Thursday, Greg",
"08-12-2016, Thursday, tug"
)
This array list how to reload in DataBase Table with coredata
I want to like this data reload in DB Table
How can i do this. I am so tried many times but do not insert array data in DataBase Table. Please help
Perfect work
long int counts=[resultss count];// resultss is a array list
for(int i=0;i<counts;i++)
{
NSArray*foos = [[resultss objectAtIndex:i] componentsSeparatedByString:#","];
NSString*date_name = [foos objectAtIndex:0];
NSString*day_name = [foos objectAtIndex:1];
NSString*name_name = [foos objectAtIndex:2];
NSLog(#"date_name %#",date_name);
NSLog(#"day_name %#",day_name);
NSLog(#"name_name %#",name_name);
//new device
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Cal" inManagedObjectContext:context];
[newDevice setValue:date_name forKey:#"date"];
[newDevice setValue:day_name forKey:#"day"];
[newDevice setValue:name_name forKey:#"pillname"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
-(void)passDataBack:(PersonHolder *)contact{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Person"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"firstName == %#",contact.firstName];
[request setPredicate:predicate];
NSError *error;
Person *person = [[self.managedObjectContext executeFetchRequest:request error:&error]lastObject];
[person.firstName setValue:contact.firstName forKey:#"fistName"];
[person.lastName setValue:contact.lastName forKey:#"lastName"];
if(![self.managedObjectContext save:&error]){
NSLog(#"Could not save edited data");
}
}
during runtime I can see that contact is loaded with all the data I'm passing through but my person entity is not getting updated.
I saw the answer how to update core data entered values and I think I am certainly missing something
You don't missing something, quite the contrary
The Core Data equivalent to the simple property setter
person.firstName = contact.firstName
is
[person setValue:contact.firstName forKey:#"firstName"];
[person setValue:contact.lastName forKey:#"lastName"];
consider also the typo #"fistName"
Edit: Try this syntax
NSArray *people = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error) {
NSLog(#"%#", error);
return;
}
if (people.count) {
Person *person = [people lastObject];
person.firstName = contact.firstName;
person.lastName = contact.lastName;
if(![self.managedObjectContext save:&error]){
NSLog(#"Could not save edited data");
}
} else {
NSLog(#"result array is empty"):
}
Instead of
[person.firstName setValue:contact.firstName forKey:#"firstName"];
[person.lastName setValue:contact.lastName forKey:#"lastName"];
use
[person setValue:contact.firstName forKey:#"firstName"];
[person setValue:contact.lastName forKey:#"lastName"];
or
person.firstName = contact.firstName;
person.lastName = contact.lastName;
Edit : a suggestion before blindly assigning last object of fetch query to person object and setting values in core data, check if your fetch query returns a result or not. This may crash.
NSArray *persons = [[[CoreDataManager sharedManager] context] executeFetchRequest:fetchRequest error:&error];
if(persons.count > 0){
// do changes in the object
}
else{
// do what you want to do to handle this situation
}
I'll try to expose my problem, because is a bit complex.
I use Core Data and I have a problem with the data stored.
When I use this code:
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"ItemMessage"];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSMutableArray *values = [[NSMutableArray alloc] init];
if (error == nil) {
for (int i = 0; i<results.count; i++) {
NSLog(#"results %#",[results objectAtIndex:i]);
ItemMessage *itemMessage = [results objectAtIndex:i];
[values addObject:itemMessage];
}
ecc. the problem is that the value printed by NSLog is correct (the "results" contains something) but the itemMessage contains always 0 key/value pairs (it seems empty).
To understand what is the problem I went back and saw that in insertNewObjectForEntityForName I have also this problem, this is the code that I used when I save the messages data in Core Data:
for (id key in objectMessage) {
ItemMessage *itemmessage = [[ItemMessage alloc] init];
itemmessage.itemMessageId = [key objectForKey:#"itemMessageId"];
itemmessage.message = [key objectForKey:#"message"];
itemmessage.sender = [key objectForKey:#"sender"];
itemmessage.users = [key objectForKey:#"users"];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newMessage;
newMessage = [NSEntityDescription insertNewObjectForEntityForName:#"ItemMessage" inManagedObjectContext:context];
[newMessage setValue: itemmessage.itemMessageId forKey:#"itemMessageId"];
[newMessage setValue: itemmessage.message forKey:#"message"];
[newMessage setValue: itemmessage.sender forKey:#"sender"];
[newMessage setValue: itemmessage.users forKey:#"users"];
[context save:&error];
if (error != nil) {
NSLog(#"Coredata error");
}
The problem is that newMessage after the insertNewObjectForEntityForName and the setValue contains also 0 key/value pairs.
Can you help me?
You don't seem to insert the new managed objects correctly into the context.
It should be:
for (id key in objectMessage) {
NSManagedObjectContext *context = [appDelegate managedObjectContext];
ItemMessage *itemmessage = (ItemMessage*)[NSEntityDescription insertNewObjectForEntityForName:#"ItemMessage"
inManagedObjectContext:context];
itemmessage.itemMessageId = [key objectForKey:#"itemMessageId"];
itemmessage.message = [key objectForKey:#"message"];
itemmessage.sender = [key objectForKey:#"sender"];
itemmessage.users = [key objectForKey:#"users"];
}
//save your inserts
To create a class file for your managed objects you could:
Go to your model file (xcdatamodeld) ->
select an entity ->
from the menu select:
Editor-> Create NSManagedObjectSubclass -> select the entities your like class files for.
Now you will have managed objects you could access with ease (NSManagedObject subclass) and benefit from CoreData features.
When you insert to manage object contest you have to call save: method, also the saving method should looks something like that:
newMessage = [NSEntityDescription insertNewObjectForEntityForName:#"ItemMessage" inManagedObjectContext:context];
// 2
newMessage.property1 = self.firstNameTextfield.text;
newMessage.property2 = self.lastNameTextfield.text;
if (![context save:&error]) {
NSLog(#"Error: %#", [error localizedDescription]);
}
i want to know how can I update a coredata record that was selected from a tableView
my code to save the coredata is:
- (IBAction)juardar:(id)sender {
NSUserDefaults *defs=[NSUserDefaults standardUserDefaults];
NSString *sedef_mat=[NSString stringWithFormat:#"%#",[defs objectForKey:#"Materia"]];
//NSLog(#"%#",sedef_mat);
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newtarea = [NSEntityDescription insertNewObjectForEntityForName:#"Tareas" inManagedObjectContext:context];
[newtarea setValue:self.Nombre.text forKey:#"nombre"];
[newtarea setValue:self.Descripcion.text forKey:#"descripcion"];
[newtarea setValue:sedef_mat forKey:#"materia"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
//NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
Thanks
Just set the new values then save the context just as you did above. But you'll be working with the fetched results:
for (Tareas *object in fetchedResultsController.fetchedObjects)
{
Tareas *t = (Tareas *)object;
if ([t.nombre isEqualToString:#"NewValue1"])
{
Tareas.nombre = #"NewValue1";
Tareas.description = #"NewValue2";
Tareas.materia = #"NewValue3";
}
}
then save context like you did above:
if (![context save:&error])
etc.