0

To make a generic code, i need to dispatch a value to a component, whatever the type of the component (UISlider,UITextField,UIWebView etc ...)

Problem : Sometimes,UIControl manage an Object type (NSString * for UITextField), and sometimes a primitive type (float for UISlider).

My Dispatcher class that dispatch a value to a component knows only : * The setter to use to set a value to a component (example : @selector(setText:) forUITextField) * The value to set

It uses KVO/KVC and i only can manipulate (id) type (so objects type because id can't hide a primitive type).

How could dispatch a float value to a UISlider to be generic ? the only way i achieve this for now is to create a category onUISlider that manages an object type and to inherit UISlider to override setValue:animated and "value" to uses my object type setter (setObjectValue: and "objectValue") :

UISlider+DataObjet.h :

@interface UISlider (DataObject)

@property (nonatomic, strong) NSNumber *objectValue;

@end


@interface MFSlider : UISlider

@end

UISlider+DataObject.m :

#import "UISlider+DataObject.h"
#import <objc/runtime.h>

static void * objectValueIdentifier = &objectValueIdentifier;

@implementation UISlider (DataObject)

-(void)setObjectValue:(NSNumber *)value{
    objc_setAssociatedObject(self, &objectValueIdentifier, value,  OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSNumber *)objectValue {
    return objc_getAssociatedObject(self, &objectValueIdentifier);
}

@end

@implementation MFSlider

-(void)setValue:(float)value animated:(BOOL) animated{
    [super setValue:value animated:animated];
    [self setObjectValue:@(value)];
}

-(float)value {
    return [[self objectValue] floatValue];
}

@end

It works, but i won't inheritsUISlider to allow users to use basicUISlider insteadMFSlider in storyboards... And i can't override basic implementation ofUISlider methods in my category (without looping ...)

Any idea ? Thx

Ashok Londhe
  • 1,491
  • 11
  • 29
QLag
  • 823
  • 1
  • 13
  • 33
  • 1
    Actually, you can kinda override implementation of `UISlider` methods in category. Take a look at method swizzling http://nshipster.com/method-swizzling/ – Jakub Vano Jun 04 '15 at 10:45
  • It's an interesting approach but i juste found my problem. I used performSelevtor:withObject to update the 'value' property instead of using "setValue:forKey" with a NSNumber * value and the key 'value'. KVC automatically converts object types into primitive types if necessery ; performing a selector does not call "'setValue:ForKey" ... – QLag Jun 04 '15 at 12:21

0 Answers0