目标 C:写入某个文本字段中包含的 csv(txt)字符串

发布于 2024-10-30 18:54:47 字数 1054 浏览 5 评论 0原文

在我的项目中,我有一个视图,在某个文本字段中写入单词,当我按下按钮时,这些字符串必须存储在 csv 文件中,如下例所示:(带有 5 个文本字段的示例)

firststring#secondstring#thirdstring#fourthstring#fifthstring;

这是我想要的结果的示例。我该怎么办?

编辑添加:

字符串的代码

 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:@";"];

最后csvString

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

正是我的字符串

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

眼眸里的那抹悲凉 2024-11-06 18:54:47

除了任何 CSV 格式问题之外,您似乎还试图写入不允许的主包。
它可能在模拟器中有效,但在设备上无效。
请参阅 中的安全性和文件系统部分iOS 应用程序编程指南

您需要在 tmp 或 Documents 文件夹中创建该文件。例如:

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

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);
谈下烟灰 2024-11-06 18:54:47

正如我的 回答您今天早些时候提出的另一个几乎相同的问题:不要这样做。

一旦用户输入“#”或“;”将 csv 文件(或者更确切地说:您所说的 CSV 文件,但实际上根本不是一个文件)写入其中一个文本字段,一旦再次读入,您的代码就会损坏并崩溃(或者至少会导致数据格式错误)。

再次强调:不要这样做。

相反:坚持使用真正的 CSV 和由专业人士编写的解析器/编写器

一般来说:除非您非常了解乔姆斯基的形式语言层次结构编写语言/文件格式解析器的经验坚持使用经过现场测试的库,而不是编码你自己的。

诸如 CSV 之类的语言/格式乍一看似乎微不足道,但绝不是(如 type -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).

疏忽 2024-11-06 18:54:47

你想要的是 Dave DeLong 的 CHCSVParser (它也支持写入 CSV)

要给出正确的答案,你需要不过请提供更多信息。

首先,您提供的字符串实际上不是有效的 CSV。
它不使用逗号(CSV 中的“C”)来分隔行字段。
它后面有一个分号,而 CSV 需要换行。

因此,要获得正确的 CSV 文件输出,您需要执行以下操作:

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

这将产生正确的 CSV à la:

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

或:

firststring,secondstring,thirdstring,fourthstring,fifthstring

取决于配置。


然而,为了获得与您的样本匹配的输出:

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

然而,后者非常容易出错。一旦这些字符串之一包含“#”、“;”或“\n”。

我的片段也使用硬编码字符串。但是,您需要为每个文本字段创建 IBOutlet 并向这些文本字段询问其字符串值。

示例:

NSString *myString = myUITextField.text;

在 OSX (<=10.6) 上,您可以使用:

NSString *myString = [myNSTextField stringValue];

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];
乜一 2024-11-06 18:54:47

看看 NSString文档 我相信您可能正在寻找:

writeToFile:atomically:encoding:error:

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

writeToFile:atomically:encoding:error:
温柔一刀 2024-11-06 18:54:47

首先,您需要在控制器对象中创建连接到文本字段的出口。然后,使用以下代码来组装 CSV 字符串:

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

然后,您可以简单地将 NSMutableString 写入扩展名为 .CSV 的文件中。

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.

旧人哭 2024-11-06 18:54:47

如果您有上面提供的字符串,请使用

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

将其写入文件使用 -

首先定义文件路径
“#define DataFilePath [@”~/Documents/a.txt”
stringByStandardizingPath]"

然后在实施

NSData *数据 =
[NSPropertyList序列化
dataFromPropertyList:[NSArray
arrayWithObjects:csvStr,nil]
格式:NSPropertyListXMLFormat_v1_0
错误描述:nil];

[数据写入文件:数据文件路径
原子地:是];

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

心碎的声音 2024-11-06 18:54:47

根据 NSString 类参考,如果您不想捕获错误详细信息,则 writeToFile 方法中的错误参数应为 NULL 而不是 nil

NSString 类参考

检查 writeToFile 方法的返回值,如果返回 NO 则说明写入文件或编码有错误:

BOOL result = [csvString writeToFile:pathToFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"Result of writeToFile: %@", result ?@"YES":@"NO");

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");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文