user3498133
user3498133

Reputation: 195

UIPickerView is not populated with data fetched from CoreData

So here is my problem. I am trying to fetch values from CoreData, my data tables have data in them thus I do not see why this occurs. When I open the view hosting the UIPickerView there is not data present.

Below is my code.

ViewController header:

#import <UIKit/UIKit.h>

 @interface EBPaymentViewController : UIViewController <UIPickerViewDelegate>

 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator    *persistentStoreCoordinator;

@property (nonatomic, strong) NSMutableArray *voucherTypes;
@property (weak, nonatomic) IBOutlet UIPickerView *voucherTypePicker;

@end

Below here is my viewDidLoad

- (void)viewDidLoad
{
     [super viewDidLoad];
     // Do any additional setup after loading the view.

     // load the data from the database and populate the UIPickerView.
     EBAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
     _managedObjectContext = [appDelegate managedObjectContext];

     NSFetchRequest *request = [[NSFetchRequest alloc] init];
     NSEntityDescription *vouchers
         = [NSEntityDescription entityForName:@"VoucherTypes"     inManagedObjectContext:_managedObjectContext];

    [request setEntity:vouchers];

     NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"voucherType" ascending:YES];
     NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:descriptor, nil];
     [request setSortDescriptors:sortDescriptors];

     NSError *error = nil;
     NSMutableArray *mutableFetchResults = [[_managedObjectContext   executeFetchRequest:request error:&error] mutableCopy];

    if(mutableFetchResults == nil)
    {
    // handle error
    }

    [self setVoucherTypes:mutableFetchResults];

}

And finally my titleForRow:

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

The UIPickerView is just empty. Any help would be appreciated!

Upvotes: 0

Views: 396

Answers (1)

RobP
RobP

Reputation: 9542

After your fetch you need to set [myPicker setDataSource:self] and then implement from UIPickerDataSource protocol the method '[pickerView:numberOfRowsInComponent:]'

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [voucherTypes count];
}

Upvotes: 2

Related Questions