How do I load data using NSEntityDescription? - iphone

i am new in xcode. i hope someone will teach me more xcode.
i'm learning core data now, from what i learn, i can save my data from uitextfield using uibutton. this is my code.
- (IBAction)button1:(id)sender
{
TestSaveDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
Highscore *record = [NSEntityDescription insertNewObjectForEntityForName:#"Highscore" inManagedObjectContext:context];
record.highscore1 = textField.text;
NSLog(#"Saved for %#", textField.text);
NSError *error;
if (![context save:&error])
{
NSLog(#"Error");
}
now i have a UILabel call label and a button2 next to it. how do i load my data in my label when button2 is pushed? Please teach me.
i already wrote like this but i dont know how to put it in my label. any tutorial that i find only put it in tableview. i don't want to put it in tableview, i just want my data show in my label.
- (IBAction)button2:(id)sender
{
TestSaveDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Highscore" inManagedObjectContext:context];
[request setEntity:entity];
NSError *error;
if (![context save:&error])
{
NSLog(#"Error");
}
}

You have to add NSPredicate to your request and execute it.
NSPredicate *predicate = <#create your predicate here#>;
[request setPredicate:predicate];
NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];
if (error) {
//inform user
}
//if you found something, you can set text for your UILabel
if ([results count]) {
Highscore *record = [results objectAtIndex:0];
label.text = record.highscore1;
}

Related

managedObjectContext deleteObject:matches not deleting data from Core data base?

Am trying to delete row from core data base in ios application buts its not working,
if (editingStyle == UITableViewCellEditingStyleDelete) {
appDelegate = [[UIApplication sharedApplication] delegate];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"PRODUCTTABLE" inManagedObjectContext:appDelegate.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
NSManagedObject *matches = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"Array Count....%d",[objects count]);
matches=[objects objectAtIndex:([indexPath row])];
NSLog(#"...%#",[matches valueForKey:#"productID"]);
NSLog(#"...%#",[matches valueForKey:#"pName"]);
NSLog(#"...%#",[matches valueForKey:#"pPrice"]);
NSLog(#"...%#",[matches valueForKey:#"pDate"]);
[appDelegate.managedObjectContext deleteObject:matches];
}
the o/p for following code:
Array Count....12
...ABC1226
...ABC-005
...599.39
...2012-08-09 05:07:50 +0000
am getting data from core data with same NSManagedObject. why delete not updating on Core data?
Save the context after changes.
NSError * error = nil;
[appDelegate.managedObjectContext deleteObject:matches];
[appDelegate.managedObjectContext save:&error];

Data gets deleted after closing the app [IOS]

I wrote an ios application in order to save a data to core data and then fetch it with the following code:
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"UserData"
inManagedObjectContext:context];
[failedBankInfo setValue:[NSNumber numberWithInt:1] forKey:#"userId"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"UserData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(#"Name: %#", [info valueForKey:#"userId"]);
}
There no problem in here. But After I close my application and modify the setvalue to 2, I only receive the last data which is 2. Earlier data (1) gets deleted.
What should I do to keep the data entries even after I close my application.
Thank You!
You need to create a UIManagedDocument to save the Core Data information. I usually create the UIManagedDocument as a property of the class. For the example I have created a UIManagedDocument called theManagedDocument:
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:#"DocumentName"];
self.theManagedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
{
[theManagedDocument openWithCompletionHandler:^(BOOL success){
if(success) [self documentIsReady];
if(!success) NSLog(#"Couldn't Open Document");
}];
}
else
{
[theManagedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if(success) [self documentIsReady];
if(!success) NSLog(#"Couldn't Create Document");
}];
}
Then I create a method called documentIsReady that is called when the document has been successfully created or opened (opened if it is already present, created otherwise). I will also keep the context as a property. Here it is called context. I also added in your code:
- (void) documentIsReady
{
if(self.theManagedDocument.documentState == UIDocumentStateNormal)
{
self.context = self.theManagedDocument.managedObjectContext;
NSError *error;
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"UserData"
inManagedObjectContext:self.context];
[failedBankInfo setValue:[NSNumber numberWithInt:1] forKey:#"userId"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"UserData" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(#"Name: %#", [info valueForKey:#"userId"]);
}
}
}
You will then want to close the document when you are done using:
[self.theManagedDocument closeWithCompletionHandler:^(BOOL success){
if(success) NSLog(#"Closed Successfully");
if(!success) NSLog(#"Error Closing Document");
}];
You did not save your new record.
[self.managedObjectContext save:nil];

App crash on using NSPredicate in iphone App?

When i am using the NSPredicate while fetch the unique user data from Coredata Entity the app getting crash. But, no error logs. This is the code am using,
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Name==%#",selectedUserName];
NSFetchRequest *fectchreq = [[NSFetchRequest alloc] init];
NSEntityDescription *entitydes = [NSEntityDescription entityForName:#"ALLData" inManagedObjectContext:managedObjectContext];
[fectchreq setEntity:entitydes];
[fectchreq setPredicate:predicate];
NSSortDescriptor *sortdes = [[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES];
NSArray *sortdesarray = [[NSArray alloc] initWithObjects:sortdes, nil];
[fectchreq setSortDescriptors:sortdesarray];
[sortdes release];
[sortdesarray release];
NSError *error = nil;
//NSMutableArray *storeddata = [[[managedObjectContext executeFetchRequest:fectchreq] error:&error] mutableCopy];
NSArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:&error];
//[fectchreq release];
NSLog(#"StoreData : %#, count : %d",storeddata, [storeddata count]);
Can anyone please help to solve this problem? THanks in advance.
NSError *error;
NSMutableArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:error];
You need to change this code to:
NSError *error = nil;
NSArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:&error];
Reasons:
The error argument should be passed as a pointer because the declaration is -executeFetchRequest:(NSFetchedRequest *)request error:(NSError **)error;
Also this method returns NSArray, not NSMutableArray - you must be getting compiler warning about this...

Record data to attributes in core data Iphone

I have about 20 entity : Event1 ... Event20
In each entity i have property values1 ... values20
I need record data in for example Event5 values8
But something wrong - may be data record in each values8 (Event1 ... Event20)
How do right?
NSString *str = [NSString stringWithFormat:#"Event%d", variable];
NSString *value = [NSString stringWithFormat:#"values%d", vari];
TermometrAppDelegate *app;
app = (TermometrAppDelegate *)[UIApplication sharedApplication].delegate;
NSFetchRequest *fetchRequests = [[NSFetchRequest alloc] init];
NSEntityDescription *entit = [NSEntityDescription entityForName:str inManagedObjectContext:app.managedObjectContext];
[fetchRequests setEntity:entit] ;
[fetchRequests setPropertiesToFetch :[NSArray arrayWithObject:value]];
[fetchRequests setReturnsDistinctResults:YES];
NSError *error;
NSArray *fetchedObject = [app.managedObjectContext executeFetchRequest:fetchRequests error:&error];
NSManagedObject *fetched = nil;
NSManagedObject *fetch = nil;
printf("\n%d", [fetchedObject count]);
The code below retrieves values in Entity5 for Value8 equal to someValueForEight.text (UITextField). This should help you out.
TermometrAppDelegate *app;
app = (TermometrAppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [app managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Entity5" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(value8 = %#)", someValueForEight.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];

Core Data confusion: fetch without tableview

I have completed and reproduced Core Data tutorials using a tableview to display contents. However, I want to access an Entity through a fetch on a view without a tableview. I used the following fetch code, but the count returned is always 0. The data exists when the database is opened using SQLite tools.
NSManagedObject *entryObj;
XYZDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Quote" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"id" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[request setEntity: entity];
NSArray *results = [managedObjectContext executeFetchRequest:request error:nil];
if (results == nil) {
NSLog(#"No results found");
entryObj = nil;
}else {
NSLog(#"results %d", [results count]);
}
[request release];
[sortDescriptors release];
count returned is always 0; it should be 5.
Can anyone point me to a reference or tutorial regarding creating a controller not to be used with a tableview.
As far as I can tell, everything looks fine (except I'm a little worried about using 'id' as an attribute name, since it's a keyword in Objective-C). Try removing the sort descriptor and see if that changes anything. Also, add an error check. Perhaps something is happening that that can tell you. And I assume "Quote" is the right name for the entity. If none of that helps, I don't think the problem is in the fetch request.
For what it's worth, here's how I would write it:
XYZDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = appDelegate.managedObjectContext;
NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Quote" inManagedObjectContext:context];
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"id" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
[request setEntity:[NSEntityDescription entityForName:#"Quote" inManagedObjectContext:context]];
NSError * error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
[request release];
if (error) {
NSLog(#"ERROR: %# %#", [error localizedDescription], [error userInfo]);
}
if (results == nil) {
NSLog(#"No results found");
entryObj = nil;
}
else {
NSLog(#"results %d", [results count]);
}