1

I've created a macro like this, and a definition:

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

I've got a method like this:

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

where i'd like to pass a dictionary of options to it like so (pseudo code):

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

It won't compile, presumably because my macro is of type NSInteger, which is not enumerable as a key for NSDictionary.

How can I implement this so I can pass an NSDictionary of options to my method?

brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • I'm confused. You have a #define that renames CustomImageOptions to be NSDictionary, then an unrelated TYPEDEF after that. What are you hoping to accomplish? – Hot Licks Dec 19 '14 at 22:20
  • Uh, well, I'm being silly I know. It's more for aesthetics than anything. I don't care so much about that, I care about being able to pass an NSDictionary of custom properties. – brandonscript Dec 19 '14 at 22:21
  • The keys to an NSDictionary must be objects. – Hot Licks Dec 19 '14 at 22:21
  • Yes... I can see that in the compiler error. I'm asking how I can implement it. – brandonscript Dec 19 '14 at 22:24
  • ??? Pass objects as keys, not integers. – Hot Licks Dec 19 '14 at 22:25
  • Yeah, so I could create some static NSStrings to use those as keys, but then I can't enforce the type of object passed. Is the only other way to do this to create a subclass of NSObject with enforced properties? – brandonscript Dec 19 '14 at 22:29
  • It's one of the blessings of duck typing. All-in-all, I'll take it over Java's retentive "generics" any day. – Hot Licks Dec 19 '14 at 22:31

1 Answers1

1

Do it this way:

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

They need to be converted to NSNumbers first.

Mobile Ben
  • 7,121
  • 1
  • 27
  • 43
  • 1
    By type checking I am assuming you mean ensuring the "key" is a proper `CGImageOption`? Yes, you're correct. The dev should use some asserts or other validation checks to ensure the key value is within the appropriate range. – Mobile Ben Dec 19 '14 at 23:01