Problem in fetching from core data to array
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];开发者_StackOverflow
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.
精彩评论