开发者

objective C: write in a csv (txt) string contained in some textfield

开发者 https://www.devze.com 2023-02-22 06:37 出处:网络
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)

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:@"#"];
[csvStr开发者_开发问答ing 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


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);


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).


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];


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

writeToFile:atomically:encoding:error:


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.


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];


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消