gpt4 book ai didi

iphone - 以编程方式创建字典属性列表

转载 作者:太空狗 更新时间:2023-10-30 03:25:16 25 4
gpt4 key购买 nike

我想以编程方式创建一个向我的 UITableView 提供数据的字典,但我遇到了困难。我想创建一个类似于 this property list (image) 的字典给予或拿走一些元素。

我看过"Property List Programming Guide: Creating Property Lists Programmatically"我想出了一个我自己的小样本:

//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];

我正在尝试将此层次结构数据用于我的 TableView 。

所以我想知道如何以编程方式创建我的属性列表(字典),以便我可以用我自己的数组填充它。

我对 iPhone 开发还很陌生,所以请多多包涵。 ;)

最佳答案

在这种情况下,“授人以鱼”比“授人以鱼”更有帮助。一旦您理解了基本原理和 NSDictionary API,就可以更轻松地制作您自己的自定义解决方案。以下是一些观察和学习要点:

  • 方法 +dictionaryWithObject:forKey: 用于创建具有单个键值对的 NSDictionary。它不会在方法调用中的每个冒号 (:) 之后接受以逗号分隔的参数,只接受一个。要创建具有多个键值对的字典,请使用 2 种相关方法之一:+dictionaryWithObjects:forKeys: 接受两个包含值和键的 NSArray 对象,或 +dictionaryWithObjectsAndKeys: 交替使用 (object, key, object, key) 终止 nil 参数。
  • 简化创建代码。你不需要一百万个局部变量来创建这个东西。在有意义的地方使用内联参数。一种方法是在代码中将字典构建为 NSMutableDictionary ,然后(如有必要)通过调用 -copy 来制作它的不可变副本。 (请记住,复制方法返回一个新对象,您必须释放该对象以避免内存泄漏。)这样您就不必为每个值都设置一个变量,这样您就可以“一次性”创建结构) 在每个级别。
  • 使用 +arrayWithObject: 创建具有单个对象的 NSArray。
  • (风格建议)切勿使用大写字母作为变量、方法或函数名称的开头。 (请注意,SO 会突出显示前导大写变量,例如类名。)它肯定会帮助阅读您代码的其他人避免因您的命名方案而对您的意图感到困惑。

只是为了让您了解在链接图像中创建字典在代码中的样子...(我忽略了您选择的变量名称并使用两种不同的方法来确保完整性。)

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];
...

关于iphone - 以编程方式创建字典属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1125048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com