In my core date in the entity name called Event and in that there is an attribute called "name". I want to fetch all the values of term from coredata to an nsarray. I used the below code and it is not working. Anybody please helpp.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, #"Error fetching events: %#\n%#", [error localizedDescription], [error userInfo]);
NSMutableArray *namesArray = [[NSMutableArray alloc]init];
namesArray = [events valueForKey:#"name"];
Your code is close and should have worked even though you were leaking memory.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, #"Error fetching events: %#\n%#", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant. You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:#"name"];
At this point you should have an array of names which are NSString instances.
The next question is -- Why? Why do you need to pull them out into an array of strings when you already have the NSManagedObject instances? Why disconnect the data from the Core Data objects.
Related
I am trying to implement simple Core Data class to store and retrieve different Language strings(array) downloaded from the server. So far I have created created Core Data template in App Delegate, created data model with one Entity "MyArray" and one Attribute "language", and written following sample code to store and retrieve these arrays. Now as both the strings arrays stored in same attribute "language", how I can retrieve Chinese language array?
// Fetch arrays code
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MyArray" inManagedObjectContext:context];
[request setEntity:entity];
NSArray *results = [context executeFetchRequest:request error:nil];
for (NSManagedObject *object in results) {
NSArray *a = [object valueForKey:#"language"];
// Use array
}
-(void)storeEnglishStrings {
NSArray *array = [[NSArray alloc] initWithObjects:#"str1",#"str2", #"str3", #"str4", #"str5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:#"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
-(void)storeChineseStrings {
NSArray *array = [[NSArray alloc] initWithObjects:#"串1",#"串2", #"串3", #"串4", #"串5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:#"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Check out the Core Data programming guide. You will need to use an NSFetchRequest
with a predicate for the chinese language. You need to make sure you can identify which one is the language of the record you are saving. I do not see the structure of your entity but I do see you are not saving the language. Also, you should reconsider your model. You usually should not need to save an NSArray into core data. You can, but it usually means your model is lacking better design.
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...
Hello I am saving number of lyrics paragraph for song Entity. now I want to update that lyrics
I used below code to update value. but it is creating new record.. and also tell to delete
- (void)editLyrics {
[editBarbutton setTitle:#"Save"];
lyrics = [NSEntityDescription insertNewObjectForEntityForName:#"Lyrics" inManagedObjectContext:managedObjectContext];
lyrics.songLyrics = lyricsTextview.text;
lyrics.startTime = startTimeText.text;
lyrics.endTime = endTimeText.text;
lyrics.lyricsSong = song;
NSError *error;
// here's where the actual save happens, and if it doesn't we print something out to the onsole
if (![managedObjectContext save:&error])
{
NSLog(#"Problem saving: %#", [error localizedDescription]);
}
}
You have to get present object before:
NSError *error = nil;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Lyrics"
inManagedObjectContext:self.moc]];
[request setPredicate:[NSPredicate predicateWithFormat:#"something what u like to filter"]];
NSArray *lyrics = [self.moc executeFetchRequest:request error:&error];
if (error) NSLog(#"Failed to executeFetchRequest to data store: %# in function:%#", [error localizedDescription],NSStringFromSelector(_cmd));
lyrics = [lyrics lastObject]
I was saving core data objects successfully until now. In this code, I'm searching for some objects and want to update or add a property to the saved object.
Apparently it won't save the changes, any idea why?
NSManagedObjectContext *managedObjectContext = ((VentoAppDelegate*) [[UIApplication sharedApplication] delegate]).managedObjectContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:EntityNameString inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"Error - Events=nil - %#", [error localizedDescription]);
}
if ([objects count] > 0) {
for (NSManagedObject* object in objects) {
if (distance <= maxDistance) {
if (bla-bla-bla) {
[object setValue:[NSNumber numberWithBool:YES] forKey:#"notification"];
[self saveContext];
}
}
}
}
Thank you!
If you change managed object it is changed only in memory. You need to save managed context after changing anything. Add something like this:
NSError *error;
if (![object.managedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
I am trying to link a value that's already in category to the wod entity. Since I do want to call a new record for each record of wod for a category. Not sure how to do this. I was thinking of using predicate but I am not exactly sure how to link it from a fetch request.
this is what my schema looks like:
Here's the code that tries to link them together:
NSManagedObjectContext *context = [self managedObjectContext];
Wod *wodInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Wods"
inManagedObjectContext:context];
[wodInfo setValue:#"Frank" forKey:#"name"];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Categories"
inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:#"(name == %#", #"Time"]];
// This is the part where i am unsure, since i am not exactly sure how to link them up
Category *category = reques
wodInfo.category =
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
Any help would be greatly appreciated.
NSError *error = nil;
NSArray *categories = [context executeFetchRequest:request error:&error];
Category *category = [categories lastObject];
wodInfo.category = category;
Be careful about your call to [context save:&error]. You are passing the address of the error variable, which is not initialized in your code and will refer to a random address, which might lead to weird errors in your application. I would recommend setting it to nil before passing it to the save: method.