Search code examples
iosobjective-ciphonecore-datauipickerview

How to get the data from the Core Data in PickerView? iOS


There is an application that has a staff list and a list of instructions . And when you create order in a TextField PickerView should appear with a list of employees ( with name ) . I will implement it as follows:

- (void)viewDidLoad {
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Employees"];
        self.empl=[[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
        UIPickerView *picker = [[UIPickerView alloc]init];
        picker.dataSource = self;
        picker.delegate = self;
        [picker setShowsSelectionIndicator:YES];
        [self.empTaskField setInputView:picker];
}



 #pragma mark - UIPickerView DataSource Method
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

        return self->_empl.count;

    }

    #pragma mark - UIPickerView Delegate Method

    -(NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
        return [_empl objectAtIndex:row];
    }

When you click the error appears on the TextField:

27/03/2016 23 : 32 : 57.177 Employee Task [ 2730 : 150090 ] - [Employees copyWithZone:]: unrecognized selector sent to instance 0x7fcf2ac84fd0 2016-03-27 23 : 32 : 57.513 Employee Task [ 2730 : 150090 ] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [Employees copyWithZone:]: unrecognized selector sent to instance 0x7fcf2ac84fd0'

How to solve this problem?


Solution

  • Remove mutableCopy . NSManagedObject doesn't comform to NSCopying protocol. So your fetch code should be

    self.empl=[managedObjectContext executeFetchRequest:fetchRequest error:nil];