0

In my project I have a view where I write words in some textfield, when I press a button these string must be stored in a csv file as this example: (example with 5 textfield)

firststring#secondstring#thirdstring#fourthstring#fifthstring;

this is an example of the result that I want. How can I do?

Edited to add:

code for the string

 NSMutableString *csvString = [NSMutableString stringWithString:textfield1.text];
[csvString appendString:@"#"];
[csvString appendString:textfield2.text];
[csvString appendString:@"#"];
[csvString appendString:dtextfield3.text];
[csvString appendString:@"#"];
[csvString appendString:textfield4.text];
[csvString appendString:@"#"];
[csvString appendString:textfield5.text];
[csvString appendString:@"#"];
[csvString appendString:textfield6.text];
[csvString appendString:@"#"];
[csvString appendString:textfield7.text];
[csvString appendString:@"#"];
if (uiswitch.on) { //switch
    [csvString appendString:@"1"];
}
else [csvString appendString:@"0"];
[csvString appendString:@";"];

finally csvString

NSLog(@"string = %@", csvString);

is exactly my string

4
  • There are no columns nor fields? Or is the string already containing delimiters and rows? Apr 7, 2011 at 10:30
  • can you plz provide string you have?
    – saadnib
    Apr 7, 2011 at 10:32
  • the string stringForCsv is ready for csv, it is a string as: 1#2#one#two#example1#example2#30; ok? Apr 7, 2011 at 10:44
  • What you're describing is no valid CSV. Instead of running your own file format you should stick to existing ones (such as CSV). And being new to Cocoa (judging from your question history) you should definitely NOT run your own format parsing/writing. Definitely NOT. In the end it's your USERS who will suffer from data corruption caused by your mistakes made due to lack of experience. Hence: stick with existing solutions written by experienced devs, such as Dave DeLong's CHCSVParser (see my answer). Also why open two identical questions if this one was answered already?
    – Regexident
    Apr 7, 2011 at 16:20

7 Answers 7

3

Aside from any CSV format issues, it also looks like you're trying to write to the main bundle which is not allowed.
It may work in the simulator but not on the device.
See the Security and The File System sections in the iOS Application Programming Guide.

You'll need to create the file in the tmp or Documents folder instead. For example:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filename = [docDir stringByAppendingPathComponent:@"Client.txt"]; 
NSError *error = NULL;
BOOL written = [csvString writeToFile:filename atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!written)
    NSLog(@"write failed, error=%@", error);
3
  • You see the file in the Documents folder but it's empty? Check that csvString is not empty. Also, perhaps unrelated and just a typo, but [csvString appendString:dtextfield3.text]; shouldn't have a "d" in front of "textfield3"?
    – user467105
    Apr 7, 2011 at 17:15
  • I see the file in the documents folder and it's empty and the string is no empty, my file is in Resource folder in the project. "d" is just an error here in the post... Apr 8, 2011 at 7:37
  • If you put csvString = [NSMutableString stringWithString:@"hello"]; right before the BOOL written = ... line, do you see "hello" in the file?
    – user467105
    Apr 8, 2011 at 13:12
2

Just as noted in my answer to another almost identical question of yours from earlier today: Don't do that.

As soon as a user enters a "#" or ";" into one of the text fields your csv file (or rather: what you call a CSV file, but actually isn't one at all) will get corrupted and crash your code once read in again (or at least result in malformed data).

Again: Do NOT do that.

Instead: stick with real CSV and a parser/writer written by a professional.

Generally speaking: Unless you have very good knowledge of Chomsky's hierarchy of formal languages and experience in writing language/file-format parsers stick with a field-tested library, instead of coding up your own.

Languages/Formats such as CSV look trivial at first glance but aren't by any means (as in type-2-language).

3
  • 1
    Well, all non-binary files containing text are txt files. What I'm saying is: go with true CSV and Dave's CHCSVParser/CHCSVWriter and not only will be able to proceed with your project way quicker than when rolling your own filetype, you'll also be standard compliant. I challenge you to provide one plausible reason to roll your own. You probably won't. So now go, read my other answer once again, download Dave's code, add it to your project and use it already. You'll thank me later. ;)
    – Regexident
    Apr 7, 2011 at 16:47
  • +1 :) If @blackguardian really needs to write stuff out with a # as a delimiter instead of a ,, then he can still use CHCSVWriter. I updated it recently to support configurable delimiters (though the default is still ,). github.com/davedelong/CHCSVParser Apr 7, 2011 at 17:00
  • horrible horrible advice "Never! attempt to write one"? How does someone learn if not to try and fail. My advice is to write it and fail at it and then write it again and fail at it again.
    – badweasel
    Jan 4, 2017 at 2:58
1

What you want is Dave DeLong's CHCSVParser (which also supports writing to CSV)

To give a proper answer you need to provide more information though.

First of all the string you provided actually is no valid CSV. It does not use commas (the "C" in CSV) to delimiter row fields. And it is trailed by a semicolon, while CSV would expect a line feed.

So to get proper CSV file output you'd do:

#import "CHCSVWriter.h"

//...

NSArray *fields = [NSArray arrayWithObjects:@"firststring", @"secondstring", @"thirdstring", @"fourthstring", @"fifthstring", nil];

CHCSVWriter *writer = [[CHCSVWriter alloc] initWithCSVFile:filePath atomic:YES];
[writer writeLineWithFields:fields];
[writer closeFile];

Which would result in a proper CSV à la:

"firststring", "secondstring", "thirdstring", "fourthstring", "fifthstring"

or:

firststring,secondstring,thirdstring,fourthstring,fifthstring

depending on configuration.


To get output matching your sample, however:

NSArray *fields = [NSArray arrayWithObjects:@"firststring", @"secondstring", @"thirdstring", @"fourthstring", @"fifthstring", nil];
NSString *outputString = [[[fields componentsJoinedByString:@"#"] appendString:@";\n"]];
[outputString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

The latter is very error prone however. As soon as one of those strings contains "#", ";" or "\n".

Also my snippets use hard-coded strings. You however would need to create IBOutlets for each text field and ask those text fields for their string values.

Example:

NSString *myString = myUITextField.text;

on OSX (<=10.6) you'd use:

NSString *myString = [myNSTextField stringValue];
0
1

Have a look at the NSString documentation i believe u might be looking for:

writeToFile:atomically:encoding:error:
0

First, you need to create outlets in your controller object that connect to your text fields. Then, use the following code to assemble the CSV string:

NSMutableString *csvString = [NSMutableString stringWithString:[textFieldOne stringValue]];
[csvString appendString:@"#"];
[csvString appendString:[textFieldTwo stringValue]];
[csvString appendString:@"#"];
[csvString appendString:[textFieldThree stringValue]];
[csvString appendString:@"#"];
[csvString appendString:[textFieldFour stringValue]];
[csvString appendString:@"#"];
[csvString appendString:[textFieldFive stringValue]];

Then you can simply write the NSMutableString to a file with a .CSV extension.

0

If you have string as you provide above the use

NSString *csvStr = [yourstring stringByReplacingOccurrencesOfString:@"#" withString:@","];

for writing it in file use -

first define filepath "#define DataFilePath [@"~/Documents/a.txt" stringByStandardizingPath]"

then in implementation

NSData *data = [NSPropertyListSerialization dataFromPropertyList:[NSArray arrayWithObjects:csvStr,nil] format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];

[data writeToFile:DataFilePath atomically:YES];

0

Per the NSString Class Reference the error parameter should be NULL not nil in the writeToFile method, if you do not want to capture error details.

NSString Class Reference

Check the return value of the writeToFile method, if it returns NO there was an error writing to the file or the encoding:

BOOL result = [csvString writeToFile:pathToFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"Result of writeToFile: %@", result ?@"YES":@"NO");
4
  • How Can I check the return value of writeToFile method? Apr 7, 2011 at 13:57
  • This means that the file is being written successfully. Is the file being created or is it just empty? Try viewing the files in your project through the Finder.
    – dhirschl
    Apr 7, 2011 at 14:34
  • the file is just empty, I try viewing the file through Finder, but it remains empty... Apr 7, 2011 at 14:37
  • Your code same is missing the initialization of the csvString variable. I would start there to see what the NSString contains.
    – dhirschl
    Apr 7, 2011 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.