UIPickerView未填充从CoreData获取的数据

时间:2014-04-10 13:59:08

标签: ios objective-c core-data uipickerview

所以这是我的问题。我试图从CoreData中获取值,我的数据表中有数据,因此我不明白为什么会发生这种情况。当我打开托管UIPickerView的视图时,没有数据存在。

以下是我的代码。

ViewController标题:

#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

下面是我的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];

}

最后我的titleForRow:

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

UIPickerView只是空的。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

获取后,您需要设置[myPicker setDataSource:self],然后从UIPickerDataSource协议实现方法&#39; [pickerView:numberOfRowsInComponent:]&#39;

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