【问题标题】:typedef NS_ENUM: passing an NSDictionary of custom properties to methodtypedef NS_ENUM:将自定义属性的 NSDictionary 传递给方法
【发布时间】:2015-02-18 21:34:15
【问题描述】:

我已经创建了一个这样的宏和一个定义:

#define CustomImageOptions NSDictionary
typedef NS_ENUM(NSInteger, CustomImageOption) {
    CustomImageOptionResize, // CGSize
    CustomImageOptionQuality, // CGFloat
    CustomImageOptionType // NSString (JPEG or PNG)
};

我有这样的方法:

- (UIImage*)imageModifiedWithOptions:(CustomImageOptions*)options;

我想像这样向它传递一个选项字典(伪代码):

[self imageModifiedWithOptions:@{CustomImageOptionResize: CGSizeMake(10, 20), CustomImageQuality: 0.9}];

它不会编译,大概是因为我的宏是 NSInteger 类型的,它不能作为 NSDictionary 的键枚举。

如何实现这一点,以便将选项的 NSDictionary 传递给我的方法?

【问题讨论】:

  • 我很困惑。您有一个 #define 将 CustomImageOptions 重命名为 NSDictionary,然后是一个不相关的 TYPEDEF。你希望完成什么?
  • 呃,好吧,我知道我很傻。审美比什么都重要。我不太关心这个,我关心的是能够传递自定义属性的 NSDictionary。
  • NSDictionary 的键必须是对象。
  • 是的...我可以在编译器错误中看到这一点。我在问如何实现它。
  • ???将对象作为键传递,而不是整数。

标签: ios objective-c nsenumerator


【解决方案1】:

这样做:

[self imageModifiedWithOptions:@{@(CustomImageOptionResize): CGSizeMake(10, 20), @(CustomImageQuality): 0.9}];

需要先转换成NSNumbers。

【讨论】:

  • 通过类型检查我假设您的意思是确保“密钥”是正确的CGImageOption?是的,你是对的。开发人员应该使用一些断言或其他验证检查来确保键值在适当的范围内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多