【问题标题】:iOS stringWithFormat shorthand WITH nil checkiOS stringWithFormat 速记 WITH nil 检查
【发布时间】:2015-01-12 08:22:07
【问题描述】:

我正在尝试为[NSString stringWithFormat] 做一个简写:

我怎样才能把这个(工作):

  #define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__]

进入这个(检查零值)

  #define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ (__VA_ARGS__ ?:@"")]

类似:

NSString *fullName = [NSString stringWithFormat:@"%@", contact.firstName ?: @""]

我尝试了不同的速记组合,但没有运气......有人有更好的主意吗?

编辑 - 找到解决方案

#define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ ?:@""]

【问题讨论】:

  • 出于好奇,为什么?似乎它只会增加另一层间接性,使了解 Objective-C 和 Foundation 类的人更难阅读您的代码。
  • 嗯,好点......基本上是为了缩短长代码,而不影响可读性......我无法想象像 fstring(@"%@", boo) 这样的东西很难阅读?
  • 编写“本机”代码更适合 XCode 自动完成和颜色编码,并且混合隐喻 可读性较差,恕我直言。
  • 谢谢 :) 我很感激,但我认为在这种情况下不会有太大的不同。当它很明显时,我宁愿少写:)
  • 我意识到这并不能回答问题,但也许为了保持代码的“本机”质量,您应该考虑为此创建一个 xcode 代码片段快捷方式:nshipster.com/xcode-snippets 我创建我经常使用它,当我简单地输入“nss”时,它会自动填充完整的语法,因为我和你一样,真的厌倦了输入(并且经常错误地大写)NSString stringWithFormat....等等等等。

标签: nsstring shorthand stringwithformat


【解决方案1】:

解决方法如下:

#define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ ?:@""]

如果你想用空字符串 if null:

#define fstringOrEmpty(...) __VA_ARGS__ ? : @""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多