简体   繁体   中英

How to export the selection of a UIPickerView object to a CSV file?

I am writing a small iOS app that I hope would facilitate my field work. I am on OS X El Capitan 10.11.4, using Xcode 7.3 and writing the app for iOS 9.3.

Here is the whole idea: instead of plugging the data in to a piece of paper I want to write everything in to a basic form-like app to be used on an iPad, and then have the app transfer the data to a .csv file.

I have pretty much everything figured out (the structure of the app, the protocol to transfer and retrieve data etc. etc.), but there is one thing that is driving me crazy. Before I show you the code that I am using, here is the problem. When I click the Save button and later on go to inspect the saved data, I cannot get the value selected by the UIPickerView objects to be transferred to the .csv file. Everything else works fine. I have two UIPickerView objects. In one I have sex information, coded as M, F, and M/F; the other has information about age coded as Adu, Juv, Hat. What I would like is for the app to save the value that is selected, but I couldn't quite figure that out.

Any help is much appreciated. Thanks.

Here is the code that I am using for my ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
@property (strong, nonatomic) IBOutlet UIDatePicker *day;
@property (strong, nonatomic) IBOutlet UITextField *species;
@property (strong, nonatomic) IBOutlet UITextField *island;
@property (strong, nonatomic) IBOutlet UITextField *cay;
@property (strong, nonatomic) IBOutlet UITextField *pit;
@property (strong, nonatomic) IBOutlet UITextField *coordinatesN;
@property (strong, nonatomic) IBOutlet UITextField *coordinatesW;
@property (strong, nonatomic) IBOutlet UIPickerView *sex;
@property (strong, nonatomic) IBOutlet UIPickerView *age;

- (IBAction)saveInfo:(id)sender;
- (IBAction)retrieveInfo:(id)sender;
- (IBAction)retractKeyboard:(id)sender;

@property (strong, nonatomic) IBOutlet UITextView *resultView;

@end

And this is the code that I am using for my ViewConntroller.m

#import "ViewController.h"

@interface ViewController ()
{
    NSArray *pickerDataSex;
    NSArray *pickerDataAge;
}
@end

@implementation ViewController

@synthesize resultView;
@synthesize day;
@synthesize species;
@synthesize island;
@synthesize cay;
@synthesize pit;
@synthesize coordinatesW;
@synthesize coordinatesN;
@synthesize sex;
@synthesize age;

- (IBAction)retractKeyboard:(id)sender {
    [self resignFirstResponder];
}

- (IBAction)saveInfo:(id)sender {
    NSString *resultLine=[NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                          self.day.date,
                          self.species.text,
                          self.island.text,
                          self.cay.text,
                          self.pit.text,
                          self.coordinatesN.text,
                          self.coordinatesW.text,
                          self.sex.dataSource,
                          self.age.dataSource];
    NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES )objectAtIndex:0];

    //resultView.text = docPath;}

    NSString *surveys=[docPath stringByAppendingPathComponent:@"results.csv"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:surveys]) {
       [[NSFileManager defaultManager] createFileAtPath:surveys contents:nil attributes:nil];
    }
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:surveys];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];
    self.species.text=@"";
    self.island.text=@"";
    self.cay.text=@"";
    self.pit.text=@"";
    self.coordinatesN.text=@"";
    self.coordinatesW.text=@"";
    NSLog(@"info saved");
}

- (IBAction)retrieveInfo:(id)sender {
    NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES )objectAtIndex:0];
    //resultView.text = docPath;
    NSString *surveys=[docPath stringByAppendingPathComponent:@"results.csv"];

    if ([[NSFileManager defaultManager] fileExistsAtPath: surveys]) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:surveys];
        NSString *surveyResults = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding];
        [fileHandle closeFile];
        self.resultView.text = surveyResults;
    }


}



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

    //Initialize picker data
    pickerDataSex = @[@"M",@"F",@"M/F"];
    pickerDataAge = @[@"Adu",@"Juv",@"Hat"];

    //Connect data to picker
    self.sex.dataSource = self;
    self.sex.delegate = self;

    self.age.dataSource = self;
    self.age.delegate = self;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//Number of columns of the data
- (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView
{
    if (pickerView==self.sex){
        return 1;
    } else if (pickerView==self.age){
       return 1;
    }

    return 0;
}

//Number of rows of data
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView==self.sex){
        return pickerDataSex.count;
    } else if (pickerView==self.age){
        return pickerDataAge.count;
    }
    return 0;
}

//The data to return for the row and component (column) that's being passed
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView==self.sex){
        return pickerDataSex[row];
    } else if (pickerView==self.age){
        return pickerDataAge[row];
    }
    return 0;
}

@end

You can get values from your UIPickerViews that way :

NSInteger selectedRowSex = [self.sex selectedRowInComponent:0];
NSInteger selectedRowAge = [self.age selectedRowInComponent:0];

NSString *selectedSex = [pickerDataSex objectAtIndex:selectedRowSex];
NSString *selectedAge = [pickerDataAge objectAtIndex:selectedRowAge];

Then

NSString *resultLine = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                      self.day.date,
                      self.species.text,
                      self.island.text,
                      self.cay.text,
                      self.pit.text,
                      self.coordinatesN.text,
                      self.coordinatesW.text,
                      selectedSex,
                      selectedAge];

You have code that populates a your picker view, but have not shown any code that gets the selected value from the picker view.

The easiest way to handle that is to add code in your saveInfo method that calls selectedRowInComponent on your picker views to get the current value.

Alternately you can implement the pickerView:didSelectRow:inComponent delegate method and read the newly selected picker value each time it changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM