objective-c 以编程方式创建字典属性列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1125048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a dictionary property list programmatically
提问by Quinn Taylor
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 list (image)give or take a couple of items.
我想以编程方式创建一个字典,将数据提供给我的 UITableView,但我很难使用它。我想创建一个类似于此属性列表(图像)的字典,提供或获取几个项目。
I've looked at "Property List Programming Guide: Creating Property Lists Programmatically"and I came up with a small sample of my own:
我看过“属性列表编程指南:以编程方式创建属性列表”,我想出了一个我自己的小样本:
//keys
NSArray *Childs = [NSArray arrayWithObjects:@"testerbet", nil];
NSArray *Children = [NSArray arrayWithObjects:@"Children", nil];
NSArray *Keys = [NSArray arrayWithObjects:@"Rows", nil];
NSArray *Title = [NSArray arrayWithObjects:@"Title", nil];
//strings
NSString *Titles = @"mmm training";
//dictionary
NSDictionary *item1 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSDictionary *item2 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSDictionary *item3 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSArray *Rows = [NSArray arrayWithObjects: item1, item2, item3, nil];
NSDictionary *Root = [NSDictionary dictionaryWithObject:Rows forKey:Keys];
// NSDictionary *tempDict = [[NSDictionary alloc] //initWithContentsOfFile:DataPath];
NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary: Root];
I'm trying to use this data of hierachy for my table views.
我正在尝试将这些层次结构数据用于我的表视图。
So I was wondering how can I can create my property list (dictionary) programmatically so that I can fill it with my own arrays.
所以我想知道如何以编程方式创建我的属性列表(字典),以便我可以用我自己的数组填充它。
I'm still new with iPhone development so bear with me. ;)
我还是 iPhone 开发的新手,所以请耐心等待。;)
回答by Quinn Taylor
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:
在这种情况下,“授人以渔”比“授人以渔”更有帮助。一旦您了解了基本原理和 NSDictionary API,您就可以更轻松地制定自己的自定义解决方案。以下是一些观察和学习要点:
- 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 terminatingnilargument. - 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
-copyon 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.
- 该方法
+dictionaryWithObject:forKey:用于创建具有单个键值对的 NSDictionary。它不会在方法调用中的每个冒号 (:) 之后接受逗号分隔的参数,只接受一个。要创建具有多个键值对的字典,请使用 2 个相关方法之一:+dictionaryWithObjects:forKeys:它接受两个包含值和键的 NSArray 对象,或者+dictionaryWithObjectsAndKeys:用终止nil参数交替(对象、键、对象、键)。 - 简化创建代码。你不需要一百万个局部变量来创建这个东西。在有意义的地方使用内联参数。一种方法是在代码中构建你的字典作为NSMutableDictionary,然后(如果需要)通过调用它来制作它的不可变副本
-copy。(请记住,复制方法返回一个必须释放的新对象,以避免内存泄漏。)这样您就不必为每个值都有一个变量,这样您就可以“一次性”创建结构) 在每个级别。 - 使用
+arrayWithObject:了与单个对象创建一个NSArray。 - (样式建议)永远不要使用大写字母作为变量、方法或函数的名称开头。(请注意,SO 突出显示了类名等前导大写变量。)它肯定会帮助阅读您的代码的其他人不会因为您的命名方案而对您的意图感到困惑。
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];
...
回答by Kendall Helmstetter Gelner
I am not sure I understand the basic objective here.
我不确定我是否理解这里的基本目标。
It seems like at runtime, you are constructing a deep dictionary with many child nodes. But you are constructing this all with static code... why can you not simply make a plist (like the one you had an image of) and read that into an NSDictionary? Both NSDictionary and NSArray have methods that let you simply read in a file and get a whole filled out object. Then it is WAY easier to edit and to understand. That method is dictionaryWithContentsOfFile.
似乎在运行时,您正在构建一个包含许多子节点的深度字典。但是你正在用静态代码构建这一切......为什么你不能简单地制作一个plist(就像你有一个图像的那个)并将它读入一个NSDictionary?NSDictionary 和 NSArray 都有一些方法可以让你简单地读入一个文件并获得一个完整的填充对象。然后编辑和理解起来就容易多了。那个方法是dictionaryWithContentsOfFile。
If all of the data is truly created at runtime before it is put into the dictionary, then it seems like you would want a very different, recursive, style of code rather than the flat examples given.
如果所有数据都是在运行时真正在将其放入字典之前创建的,那么您似乎需要一种非常不同的、递归的代码风格,而不是给出的平面示例。
Lastly, I personally dislike the dictionaryWithObjects:forKeys:method in NSDictionary for building a dictionary. If you have to do things that way I greatly prefer the alternate method dictionaryWithObjectsAndKeys:which does the same thing but keeps the keys with the objects:
最后,我个人不喜欢dictionaryWithObjects:forKeys:NSDictionary 中构建字典的方法。如果您必须这样做,我非常喜欢替代方法dictionaryWithObjectsAndKeys:,它可以做同样的事情,但将键与对象保留在一起:
NSDictionary *item1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"Screen J",
@"Title",
[NSNumber numberWithInt:3],
@"View"];
回答by catsby
NSMutableDictionary *topLevel = [NSMutableDictionary dictionary];
NSMutableDictionary *item1 = [NSMutableDictionary dictionary];
NSString *item1title = [NSString stringWithString:@"Title 1"];
NSMutableDictionary *item1children = [NSMutableDictionary dictionary];
// create children
NSString *item1child1 = [NSString stringWithString:@"item 1, child 1"];
NSMutableDictionary *item1child2 = [NSMutableDictionary dictionary];
NSString *item1child2title = [NSString stringWithString:@"Title 1-2"];
NSMutableDictionary *item1child2children = [NSMutableDictionary dictionary];
NSString *item1child2child1 = [NSString stringWithString:@"item 1, child 2, child 1"];
NSString *item1child2child2 = [NSString stringWithString:@"item 1, child 2, child 2"];
[item1child2 setObject:item1child2title forKey:@"Title"];
[item1child2children setObject:item1child2child1 forKey:@"item 1 child2 child 1"];
[item1child2children setObject:item1child2child2 forKey:@"item 1 child2 child 2"];
[item1child2 setObject:item1child2children forKey:@"children"];
// add children to dictionary
[item1children setObject:item1child1 forKey:@"item1 child1"];
[item1children setObject:item1child2 forKey:@"item1 child2"];
// add to item 1 dict
[item1 setObject:item1title forKey:@"Title"];
[item1 setObject:item1children forKey:@"children"];
NSMutableDictionary *item2 = [NSMutableDictionary dictionary];
NSString *item2title = [NSString stringWithString:@"Title"];
NSMutableDictionary *item2children = [NSMutableDictionary dictionary];
NSString *item2child1 = [NSString stringWithString:@"item 2, child 1"];
NSString *item2child2 = [NSString stringWithString:@"item 2, child 2"];
NSString *item2child3 = [NSString stringWithString:@"item 2, child 3"];
// add children to dictionary
[item2children setObject:item2child1 forKey:@"item2 child1"];
[item2children setObject:item2child2 forKey:@"item2 child2"];
[item2children setObject:item2child3 forKey:@"item2 child3"];
// add to item 2 dict
[item2 setObject:item2title forKey:@"Title"];
[item2 setObject:item2children forKey:@"children"];
[topLevel setObject:item1 forKey:@"Item 1"];
[topLevel setObject:item2 forKey:@"Item 2"];
回答by catsby
first of .. super! thanks .. I really appreciate the explanation and code snippet. Since you gave me such a good explanation I hope you don't mind me asking a couple more questions.
第一个..超级!谢谢..我非常感谢解释和代码片段。既然你给了我这么好的解释,我希望你不介意我再问几个问题。
First, I did as you suggested and this is what I came up with : (I used my original property list instead of the example this time so this is where the drilldown table gets his( or needs to get his ) treestructure).
首先,我按照你的建议做了,这就是我想出的:(这次我使用了我的原始属性列表而不是示例,所以这是钻取表获取他的(或需要获取他的)树结构的地方)。
http://img509.imageshack.us/img509/7523/picture2lsg.png
http://img509.imageshack.us/img509/7523/picture2lsg.png
NSDictionary *root = [NSMutableDictionary dictionary];
NSDictionary *item1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:@"VirtuaGym Online"] forKey:[NSArray arrayWithObjects:@"Title"]];
NSDictionary *item2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:@"Do the training"] forKey:[NSArray arrayWithObjects:@"Title"]];
NSDictionary *item3 = ...
[root setObject:item1 forKey:@"Item 1"];
[root setObject:item2 forKey:@"Item 2"];
Also did some research and tried something else with some other input..
还做了一些研究,并尝试了其他一些输入。
NSMutableArray *Rows = [NSMutableArray arrayWithCapacity: 1];
for (int i = 0; i < 4; ++i) {
NSMutableArray *theChildren = [NSMutableArray arrayWithCapacity: 1];
[theChildren addObject: [NSString stringWithFormat: @"tester %d", i]];
NSString *aTitle = [NSString stringWithFormat: @"Item %d", i];
NSDictionary *anItem = [NSDictionary dictionaryWithObjectsAndKeys: aTitle, @"Title", theChildren, @"Children"];
[Rows addObject: anItem];
}
NSDictionary *Root = [NSDictionary withObject: Rows andKey: @"Rows"];
I decided to just test both of these however it does what I want. It gives me a EXC_BAD_ACCESSerror.
我决定只测试这两个,但它可以满足我的需求。它给了我一个EXC_BAD_ACCESS错误。
I was also wondering since I saw you using number in your code snippet, couldn't you also use NSString since that's what the plist uses.. could be totally of here of course
我也想知道,因为我看到你在你的代码片段中使用了数字,你不能也使用 NSString 因为那是 plist 使用的......当然可以完全在这里
NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Screen J",[NSNumber numberWithInt:3],nil]
forKeys:[NSArray arrayWithObjects:@"Title",@"View",nil]];
and third a question is about my possible approach to my app. I have an xml parser which saves certain information in different arrays. I want to use this information for my drilldown UITableviews (infoFirstScreen[] infoSecondScreen[] infoThirdScreen[]). The information provided has to be connected like the tree I showed you above. This is the reason I wanted to build the dictionary in code so I can take the info from my arrays and insert it here. My question do you think my approach is correct, wrong or is there a faster way?
第三个问题是关于我对我的应用程序的可能方法。我有一个 xml 解析器,它将某些信息保存在不同的数组中。我想将此信息用于我的向下钻取 UITableviews (infoFirstScreen[] infoSecondScreen[] infoThirdScreen[])。提供的信息必须像我上面展示的树一样连接。这就是我想在代码中构建字典的原因,以便我可以从数组中获取信息并将其插入此处。我的问题你认为我的方法是正确的,错误的还是有更快的方法?
again really appreciate the explanation ;)
再次非常感谢解释;)

