Frage

Fair warning: I know absolutely no Objective-C. I am using the Foundation module for PyObjC.

I have a dictionary which I use to create an NSDictionary. An example:

from Foundation import NSDictionary
d = {'a': 1, 'b': 2, 'c': 3}
nsd = NSDictionary(d)

I know that I can write the contents of nsd to a file with nsd.writeToFile_atomically_(), but I can't figure out how to just get a string which contains all the plist-y XML. You might reckon that I could use a StringIO object, but:

>>> import StringIO
>>> s = StringIO.StringIO()
>>> nsd.writeToFile_atomically_(s,True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: NSInvalidArgumentException - Class OC_PythonObject: no such selector: getFileSystemRepresentation:maxLength:

I can't make heads or tails of the help pages, and I've tried searching SO and the web at large and people seem more interested in doing the converse of what I'm trying to do.

What I would like is to be able to do something like this:

plst = nsd.asPlistyString_()

Or maybe I have to use an NSSString, I wouldn't know:

plst = NSString.makePlistyStringFromDictionary_(nsd)

Either way, plst would be something like "<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC" yada yada. Can someone point me in the right direction?

Edit: I am aware of plistlib but I'm trying to do this directly with Foundation to help my my code future-compatible. (plistlib is pretty nice, though.)

War es hilfreich?

Lösung 2

Something like this should work for you. You basically need to use NSPropertyListSerialization to serialize the dictionary as xml.

from Foundation import NSDictionary, NSString, NSPropertyListSerialization
from Foundation import NSUTF8StringEncoding, NSPropertyListXMLFormat_v1_0

d = {'a': 1, 'b': 2, 'c': 3}
nsd = NSDictionary(d)

# serialize the dictionary as XML into an NSData object
xml_plist_data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(nsd, NSPropertyListXMLFormat_v1_0, 0, None)

if xml_plist_data:
    # convert that data to a string
    xml_plist = NSString.alloc().initWithData_encoding_(xml_plist_data, NSUTF8StringEncoding)
else:
    # look at the error
    pass

Andere Tipps

While this doesn't directly answer your question, you could do this much more easily with the standard library module plistlib:

import plistlib
d = {'a': 1, 'b': 2, 'c': 3}
plist_string = plistlib.writePlistToString(d)

Result:

<?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">
<dict>
    <key>a</key>
    <integer>1</integer>
    <key>b</key>
    <integer>2</integer>
    <key>c</key>
    <integer>3</integer>
</dict>
</plist>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top