IOS:在数组的文件txt中写一个字符串

时间:2011-07-04 09:15:51

标签: ios xcode string text-files

我有一个由其他数组组成的数组:

示例我的数组里面有两个数组:

myArray = [(element1,element2,element3)],[(element4,element5,element6)] 这只是一个示例,表明myArray有两个数组(这些元素是字符串)

现在我希望以这种方式在txt文件中写入这些元素:

 element1#element2#element3;element4#element5#element6;

创建此字符串以在txt文件中写入的代码是什么?

1 个答案:

答案 0 :(得分:16)

    NSMutableString *printString = [NSMutableString stringWithString:@""];
    for(i=0;i<[myArray count];i++)
    {
        for (NSString element in [myArray objectAtIndex:i])
        {
            [printString appendString:[NSString stringWithFormat:@"%@#",element] ];
        }
        [printString appendString:@";"];
    }

    //CREATE FILE

    NSError *error;

    // Create file manager
    //NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSString *documentsDirectory = [NSHomeDirectory() 
                                    stringByAppendingPathComponent:@"Documents"];

    NSString *filePath = [documentsDirectory 
                          stringByAppendingPathComponent:@"fileArray.txt"];

    NSLog(@"string to write:%@",printString);
    // Write to the file
    [printString writeToFile:filePath atomically:YES 
            encoding:NSUTF8StringEncoding error:&error];