Reputation: 227
I have an Entity called Devices in CoreData. Devices have following attributes: Name, model, manufacturer, owner. All attributes are of string type. I am using the following code to fetch values from Entity devices using predicate
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Devices" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
request.fetchLimit = Device_LIMIT;
NSSortDescriptor *sortDisc = [NSSortDescriptor sortDescriptorWithKey:@"model" ascending:YES];
[request setSortDescriptors:@[sortDisc]];
NSError *error;
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
if (array) {
arrName = [array valueForKey:@"Name"];
}
return arrName;
I am getting the desired result this way.But, my question is how can I directly fetch an array from Device Entity for Name attribute, without adding any if-else or for in condition.
Upvotes: 0
Views: 899
Reputation: 70976
You need to fetch an array from Core Data to get these values-- that's just how Core Data works. You could change your code to use NSDictionaryResultType
, but then you'd just get an array of dictionaries instead of an array of managed objects. What you're doing is correct, an there's no short cut to get name values without getting an array and extracting the names from that array.
Upvotes: 0
Reputation: 119
The return value for the method executeFetchRequest
is an objects array, so you must use a for-loop to take the name attribute out.
Upvotes: 0
Reputation: 1144
A nil array is only returned if the fetch request failed with an error.
Your code should be structured such that if there is no array, you should deal with the error.
EDIT: This is fairly true for most methods that return something and take an error as an argument in cocoa. Usually if nothing is returned, then the error should be checked.
Upvotes: 0
Reputation: 3301
Do a for-loop to add values to arrName
as:
NSMutableArray *arrName = [NSMutableArray new];
for (NSManagedObject *object in array) {
[arrName addObject:object[@"Name"]];
}
Upvotes: 0