【问题标题】:Adding data to an NSDictionary... SRSLY? Isn't there a quicker way?将数据添加到 NSDictionary... SRSLY?没有更快的方法吗?
【发布时间】:2023-04-01 06:45:01
【问题描述】:

我来自 Flash ActionScript 背景。我来自哪里,我可以像这样设置一个类似字典的对象:

var data:Object = {startPoint:5, endPoint:12};

所以来到 Objective-C,我惊讶地发现与此等价的似乎是:

NSMutableDictionary *data = [NSMutableDictionary dictionary];
[data setObject:[NSNumber numberWithInt:5] forKey:@"startPoint"];
[data setObject:[NSNumber numberWithInt:12] forKey:@"endPoint"];

肯定有更简单的方法……或者这真的是我的命运?

【问题讨论】:

  • 为什么感到惊讶?并非所有语言都相同。
  • 但有些语言比其他语言更冗长。 ;) 我实际上可以从扩展的 NSObject 中创建一个值对象,并在其上定义属性......这将使语法更短。

标签: iphone objective-c nsmutabledictionary nsnumber verbose


【解决方案1】:

这是我能想到的唯一更短的方法:

NSMutableDictionary *petalData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"startPoint", [NSNumber numberWithInt:12], @"endPoint", nil];

【讨论】:

  • 是的,虽然因为它太冗长,我将它分成不同的行以使其更具可读性。
猜你喜欢
  • 2015-05-07
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多