Create a dictionary property list programmatically

后端 未结 4 1878
清酒与你
清酒与你 2021-02-06 00:40

I want to programatically create a dictionary which feeds data to my UITableView but I\'m having a hard time with it. I want to create a dictionary that resembles this property

4条回答
  •  悲&欢浪女
    2021-02-06 01:13

    This is a situation where "teach a man to fish" is a vastly more helpful approach than "give a man a fish". Once you understand the basic principles and the NSDictionary API, it becomes much easier to craft your own custom solution. Here are a few observations and learning points:

    • The method +dictionaryWithObject:forKey: is used to create an NSDictionary with a single key-value pair. It will not accept comma-separated arguments after each colon (:) in the method call, just one. To create a dictionary with multiple key-value pairs, use one of 2 related methods: +dictionaryWithObjects:forKeys: which accepts two NSArray objects containing values and keys, or +dictionaryWithObjectsAndKeys: which alternates (object, key, object, key) with a terminating nil argument.
    • Simplify the creation code. You don't need a million local variables just to create the thing. Use inline arguments where it makes sense. One way to do this it to build up your dictionary in code as an NSMutableDictionary, then (if necessary) make an immutable copy of it by calling -copy on it. (Remember that a copy method returns a new object that you must release to avoid memory leaks.) That way you don't have to have a variable for every single value so you can do a "one shot" creation of the structure(s) at each level.
    • Use +arrayWithObject: for creating an NSArray with a single object.
    • (Style suggestions) Never use an uppercase letter to begin the name of a variable, method, or function. (Notice that SO highlights leading-caps variables like class names.) It will certainly help others who read your code from being confused about your intent by your naming scheme.

    Just to give you a flavor of what creating the dictionary in the linked image might look like in code... (I'm ignoring your chosen variable names and using both different approaches for completeness.)

    NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Screen J",[NSNumber numberWithInt:3],nil]
                                                      forKeys:[NSArray arrayWithObjects:@"Title",@"View",nil]];
    NSDictionary *item2 = [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"Screen I", @"Title", 
                                            [NSArray arrayWithObject:item1], @"Children", 
                                            nil];
    ...
    

提交回复
热议问题