0

My app requires the ability to take a String and save it to an NSDictionary as an NSData object, such that when the NSDictionary is written to a .plist file the resulting file contains the data as <data>The String as the user typed it (no encoding)</data>. Is there anyway to do that without manually writing the XML for the .plist file?

Thanks in advance for any help.

Benjy Wiener
  • 1,085
  • 2
  • 9
  • 27

1 Answers1

3

There's no way to do what you want.

First, it makes no sense to claim that you don't want the string encoded. Encoding is the process of producing a byte stream from a string. Without encoding, there's no representation of the string. Strings are abstract. They have no concrete representation in and of themselves. Only encoding produces that.

Anyway, that's just not how NSData objects are serialized to property list files. Even if you manually wrote the file, it wouldn't really be a correct property list file and no other property-list-reading program would be able to parse it. How did you come to conclude that your app requires this ability?

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • To answer your question of how I came to conclude that my app requires this ability, my app is a property list editor. What I would like is the equivalent of `"\(myTextView.text)`, but without manually writing the XML. Just to be sure, are you saying that this is impossible? (I'm not sure if my original question was completely clear.) – Benjy Wiener Jul 24 '15 at 01:09
  • It's possible to write any file contents you like, but what you describe would not be a plist file that any other app would be able to parse. The `data` element of the property list XML schema is a Base64-encoded byte stream. If some other plist-reading app tries to read your format, it will attempt to Base64-decode plain text and get an error at best or garbled data at worst. Beyond that, `myTextView.text` may not be valid to just insert into XML, anyway. If you're writing a property list editor, you should use `NSPropertyListSerialization` to serialize the objects. – Ken Thomases Jul 24 '15 at 01:51
  • My intention was to have a `UITextView` where the user could enter pre-Base64-encoded text. It seems it would make more sense to just leave data objects out, as they are probably (almost) never written manually. – Benjy Wiener Jul 24 '15 at 02:03
  • If your users are actually interested in entering data objects, you could build various interface mechanisms. Let them pick a file. Let them enter data in other forms (plain text, images, color picker, etc.) and specify an appropriate conversion. Add a hex editor interface or something. If you're going to let them enter Base64-encoded data as text, then your program should decode it, store the resulting byte stream in an `NSData`, put that in the object hierarchy, and serialize it in the plist like normal. – Ken Thomases Jul 24 '15 at 03:15