views:

39

answers:

3

Hi everyone

I load from a txt file many info, and I would like, if possible, to dynamically create NSmutable dictionary with the elements of the txt.

For example, each is like that: id of element | date | text

What I'm asking is the equivalent of the NSString stringWithFormat:. Can we do the same for an Mutable Dictionary?

To be more practical, let's say the NSString *date is equal to "23/12/2009" (for europe). I want to create a dictionary called 23/12/2009 without declaring *23/12/2009 but just something like dictionaryWithFormat: @"%@", date];

I'm stuck on this, and I don't even know if it is possible. If not, what's the best way to approach that?

Thanks everyone

Regards

A: 

To separate the components of the string, you can use -[NSString componentsSeparatedByString:], which returns an NSArray of strings. To get the date from the string, you can use -[NSDateFormatter dateFromString:]. If you need more complicated parsing, you can look at NSScanner.

eman
A: 

Sounds like you want a dictionary of dictionaries. Make each dictionary you want, and then insert it into another parent dictionary, using that date, e.g., as its key.

Jim
It's already done for the others, but I don't see how to do there without manually initialising each dictionary, cause I've like 150 dates...
Bruno
A: 

Can you make the txt file into an xml file instead? Then you could call the dictionaryWithContentsOfFile: method to create the NSMutableDictionary from the file.

You can have multiple dictionaries in an xml file by defining an array in the xml file and read it using NSArray's arrayWithContentsOfFile method. Or you can have dictionaries of dictionaries in an xml file, that's what I use in my ClockSmith app to keep track of all the clock components and their settings. Here's an excerpt from an xml file to give you an idea. It was created with NSDictionary's writeToFile:atomically: method.

<?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"&gt;
<plist version="1.0">
<dict>
    <key>290900405.808</key>
    <dict>
        <key>Description_Key</key>
        <string>Digital Clock - AM/PM</string>
        <key>NIB_Name_Key</key>
        <string>ClockDigital12Hr</string>
        <key>Option_Value_Key</key>
        <integer>3</integer>
    </dict>
    <key>290900405.810</key>
    <dict>
        <key>Description_Key</key>
        <string>One Day Calendar</string>
        <key>NIB_Name_Key</key>
        <string>CalendarDay</string>
        <key>Option_Value_Key</key>
        <integer>0</integer>
    </dict>
</dict>
</plist>
progrmr
It could be a good solution but I want to have a dictionary for each date, parent and children, so I still need to create many dictionaries easily
Bruno