I have an iOS app that uses Core Data to persist information retrieved from a server. I use a basic fetch request to grab all the managedObjects
for a given entity
. The managedObjects
are put into an array which I use to populate a tableViewController
. Each cell in the table has a UITextField
that I am trying to put the information into. I can get the data into the text field but each element comes with parentheses around them. How can I get rid of these and just show the text?
Here is the fetch request:
NSManagedObjectContext *moc = self.managedObjectContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"UserInfo" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSArray *objects = [moc executeFetchRequest:request error:&error];
Here is what I am using to populate the text fields:
self.middleNameField.text = [[objects valueForKey:@"firstName"] description];
self.middleNameField.text = [[objects valueForKey:@"middleName"] description];
self.lastNameField.text = [[objects valueForKey:@"lastName"] description];
Here is what the response looks like
This question has been asked a few times but all seem to be looking to display all contents of the array at once rather than a particular element. Some recommend the method below.
self.firstNameField.text = [[[objects valueForKey:@"firstName"] stringByReplacingOccurrencesOfString:@"(" withString:@""]description];
But I get this exception error.
-[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance
Could someone point me in the right direction on this? I realize I may be going about this all the wrong way. Don't hesitate to recommend a better method to accomplish the same task. Snippets Really Help!
Your code returns an array because you are asking an array for valueForKey
[objects valueForKey:@"firstName"]
I would suggest this:
NSArray *objects = [moc executeFetchRequest:request error:&error];
NSManagedObject *object = [objects lastObject];
if (object) {
self.middleNameField.text = [object valueForKey:@"firstName"];
self.middleNameField.text = [[object valueForKey:@"middleName"];
self.lastNameField.text = [[object valueForKey:@"lastName"];
}
You may want to set those fields to @"" if the objects array is empty. Depends on whether they could have been populated before.
I'm also not a fan of using NSManagedObject *object if you can use the proper subclass generated for your model. Assuming that the class in question is Person
Person *person = [objects lastObject];
if (person) {
self.middleNameField.text = person.firstName;