I noticed that when saving a file from within an iOS App using:
writeToFile:myFile atomically:YES

the resulting file is actually saved in XML format, and always has the following code:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>Sentence 1</string>
    <string>Sentence 2</string>
    <string>Sentence 3</string>
    <string>Sentence 4</string>
</array>
</plist>

So its always in an XML/Plist format.

But if I try to import into the App a text file which was NOT created from within an iOS App - it doesn't seem to know how to recognize it.

For example, if I take a plain text file created in TextEdit and drag it into my App's Documents folder and then run the App again, the App sees this new file, but when I try to load its contents using: initWithContentsOfFile:myFile
the result I get is: (null)

Is this because the default format of files created in TextEdit is ".rtf"? Or should I be using an altogether different method to read plain-text files into the App other than initWithContentsOfFile:myFile?

Ultimately I'd like for the App to be able to load existing text files - maybe even Microsoft WORD files - and work with them. I'd like for the user to drag their existing files into the App's folder in iTunes, and then sync their device with iTunes - which will then copy these new files onto the device and when they run their App again, the app will see the new files and be able to open them and read their contents.

Any suggestions?

有帮助吗?

解决方案

You've mentioned the writeToFile:atomically: method but you haven't told us what class this method is being called on. For example, NSString, NSArray, NSDictionary and other classes have a method with this name and they all behave differently as might expect given teh different types of data structures.

From the above file output, it looks like you're probably calling this on an NSArray which is why it gets written in Plist format. I assure you that strings get written plainly if you using an NSString, eg:

NSString *s = @"A string";
[s writeToFile:path atomically:YES];

will produce a file with:

A String

You may want to convert various other data structures into a string before you write it to a file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top