3

I have some properties set up on an object, mostly GLfloat and I was wondering if there was a way to use [self setValue:(id)value forKey:(id)key]; that would take a c style variable?

It doesn't have to be setValue:forKey if there is an alternative if there is one available.

My reasoning is I have a lot of properties on an object that are floats and I can pass an NSDictionary with values (NSNumber here is no issue) to set each relevant value.

Ideally I could do this without enumerators or custom setters - is this doable?

Hugo Scott-Slade
  • 896
  • 9
  • 16
  • You can always use NSValue objects to "wrap" other entities. Not necessarily convenient. But, of course, NSNumber works for floats. – Hot Licks Feb 21 '13 at 12:37

2 Answers2

4

You can automatically box any value into a NSNumber using the new Objective-C syntax:

GLfloat alpha;
alpha = 2.3f;

[self setValue:@(alpha) forKey:@"theKey"];

This will automatically convert the float into an NSNumber for you with minimal fuss.

Richard Brown
  • 11,346
  • 4
  • 32
  • 43
4

Similarly, setValue:forKey: determines the data type required by the appropriate accessor or instance variable for the specified key. If the data type is not an object, then the value is extracted from the passed object using the appropriate -Value method.

You can pass an NSNumber, and it will be automatically converted back into a float for your setter.

@interface MyClass ()

@property (nonatomic, assign) CGFloat example;

@end

@implementation MyClass

- (void)testSetter {
    [self setValue:@(5.0f) forKey:@"example"];
}

@end
kylef
  • 1,066
  • 1
  • 8
  • 11
  • How is your answer different to the other answer? – trojanfoe Feb 21 '13 at 13:00
  • The other answer didn't explain weather the property is still a float, or weather the property is a NSNumber. (The automatic value conversion) – kylef Feb 21 '13 at 13:01