A header row in a CSV file is simply fixed data in the first row - it is up to the program that reads the CSV file to treat the first row as a header row - Excel has an option in the file open/import dialog, for example.
In your code you can simply write the header when you first create the file -
- (IBAction)save:(id)sender
{
NSString *headerRow;
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
headerRow=@"name,city,state";
}
NSString * writeString = [NSString stringWithFormat:@"%@,%@,%@\n", self.nameTextField.text, self.cityTextField.text, self.stateTextField.text];
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath]];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
if (headerRow != nil) {
[handle writeData:[headerRow dataUsingEncoding:NSUTF8StringEncoding]];
}
[handle writeData:[writeString dataUsingEncoding:NSUTF8StringEncoding]];
self.nameTextField.text = @"";
self.cityTextField.text = @"";
self.stateTextField.text = @"";
[self.stateTextField resignFirstResponder];
}