objective-c - NSDictionary Objective-C

标签 objective-c cocoa

我正在尝试以字符串作为键以以下方式存储数据,我想要一个数组作为值。

关键对象

“字母”{'a','b','c','d'}
“数字”{1,2,3,4,5,6,7}

在代码中使用 NSDictionary 是否可行?如果是这样,那会是什么样子?我真的很困惑。

最佳答案

一种在代码中执行此操作的简单方法(这只是您可以执行此操作的多种方法之一):

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSArray arrayWithObjects:@"a", @"b", @"c", @"d", nil] forKey:@"letters"];
[dict setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil] forKey:@"numbers"];

它创建了一个 NSDictionary,其中包含一个字符串数组和一个 NSNumber 对象数组,还有其他创建数组的方法,但它演示了一种基本方法.

根据以下评论:

如果您想一次向数组添加项目...

  // create the dictionary and add the letters and numbers mutable arrays
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  NSMutableArray *letters = [NSMutableArray array];
  NSMutableArray *numbers = [NSMutableArray array];
  [dict setObject:letters forKey:@"letters"];
  [dict setObject:numbers forKey:@"numbers"];

  // add a letter and add a number
  [[dict objectForKey:@"letters"] addObject:@"a"];
  [[dict objectForKey:@"numbers"] addObject:[NSNumber numberWithInt:1]];  
  // This now has an NSDictionary (hash) with two arrays, one of letters and one 
  // of numbers with the letter 'a' in the letters array and the number 1 in 
  // the numbers array

关于objective-c - NSDictionary Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/908742/

相关文章:

objective-c - 关于 Mac 开发的死树期刊?

objective-c - cocoa NSView 模糊背景

objective-c - 来自 UIView 的图像

objective-c - 为什么将此协议(protocol)添加到此类别会触发编译器警告?

objective-c - Cocoa/Objective-C - 从其他窗口层发送/接收点击?

cocoa - 开始使用适用于 OS X 的 Cocoa?

objective-c - 如何在 OS X 上的 CALayer 上获得流畅/清晰的文本

objective-c - setModalTransitionStyle 和 setModalPresentationStyle,设置 View 大小

ios - 防止 NSString 的堆检查

第二次单击导航 Controller 后,ios自定义委托(delegate)为空