简体   繁体   中英

Cocoa / Objective-C write nested strings/data to a file, how?

I need to create an xml .plist with 6 records, with record 5 being an input string from the user, the rest is all fixed data. I'm not sure what the best way of doing this is? It seems like it should be simple, but I haven't had much success.

The data that needs to be written looks like this:

<?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>AREA51</key>
    <dict>
       <key>ORIGIN</key>
       <data>M45</data>

          ...(4 more records)... 

              (USER STRING) 

          ...(1 more record)...

   </dict>
</dict>
</plist>

I've tried following some examples, but I think they are outdated and not up to spec. thanks!

I don't know how a tutorial for this could possibly be outdated, the way you do it hasn't changed in something like ten years. Create the dictionary, and use the -writeToFile:atomically: method.

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    // object first...
    [NSDictionary dictionaryWithObjectsAndKeys:
        @"M45", @"ORIGIN", // object first, then key
        ... // repeat
        nil],
    // then key...
    @"AREA51",
    nil];
[dict writeToFile:path atomically:NO];

(I don't know if you actually need atomic writing or not. It is safe to change it to YES if you are unsure.)

Entries in a dictionary * are unordered, so you shouldn't expect the user's entry to be at any particular position. Instead, you use the key to retrieve the data, so you might have:

<dict>
   <key>ORIGIN</key>
   <data>M45</data>
   <key>USERENTRY</key>
   <data>Hello world!</data>
   ...
</dict>

or it might be:

<dict>
   <key>USERENTRY</key>
   <data>Hello world!</data>
   <key>ORIGIN</key>
   <data>M45</data>
   ...
</dict>

or some other order. Deitrich Epp's instructions for writing the plist should be all you need to write the data. Just realize that you can use any object for the data, including the user's string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM