When you need to retrieve data from the context, an NSFetchRequest is used. Using an NSFetchRequest is conceptually the same as a SQL Query. For example, the following snippet of code will retrieve all instances of an entity stored in the application’s context:
NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; NSEntity *entity = [NSEntityDescription entityForName:@"ExampleEntity" inManagedObjectContext:context]; [request setEntity:entity]; NSError *error; NSArray *result = [context executeFetchRequest:request error:"error]; NSAssert(result != nil, ([NSString stringWithFormat:@"Error fetching entity: %@", error]));
In this example, a request object is allocated and initialized. An NSEntity object is retrieved from the context that represents the Entity we are retrieving from the context. The Entity is then added to the to the fetch request. Finally, the request is executed against the context. The execution of the request returns an NSArray of all entities that match the requirements. In this example, it would return an array of every ExampleEntity in the context.