How to save a NSMutableDictionary into a file in documents?

后端 未结 2 1758
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 08:09

I would like to save the content of a NSMutableDictionary object to a file. How do I do this ? I already know how to do this task with a NSDictionary object but I don\'t know ho

2条回答
  •  再見小時候
    2021-01-25 08:28

    If you just swing over to the NSDictionary documents. You will see there is a method for saving a dictionary to a file

    writeToFile:atomically:

    Writes a property list representation of the contents of the dictionary to a given path.

    - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
    

    Parameters

    path: The path at which to write the file. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

    flag: A flag that specifies whether the file should be written atomically.

    If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

    Return Value

    YES if the file is written successfully, otherwise NO.

    This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

    If the dictionary’s contents are all property list objects, the file written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfFile: or the instance method initWithContentsOfFile:.

    So the piece of code you are looking for is probably something like:

    [myDict writeToFile:path atomically:YES]
    

    where myDict is the dictionary you have and path is the path to the location you want to save it to

提交回复
热议问题