Skip to content

wrap primitive values into NSValue

Aleksey Garbarev edited this page Jul 30, 2014 · 7 revisions

To pass primitive values into assembly interface as run-time argument wrap them into NSValue.

All primitive values can be wrapped into NSValue (or its subclass NSNumber). See examples below for details.

Example1: Inject scalar values

For example you have an object:

@interface People : NSObject
@property (nonatomic, string) NSString *name;
@property (nonatomic) NSUInteger age;
@end

and you want to inject age property as run-time argument. Prepare definition for that:

- (People *)peopleWithAge:(NSNumber *)age
{
    return [TyphoonDefinition withClass:[People class] configuration:^(TyphoonDefinition *definition) {
        [definition injectProperty:@selector(age) with:age];
    }];
}

then call your factory via assembly interface, like this:

People *people = [factory peopleWithAge:@23]; //Passed NSNumber will be unwraped into NSUInteger

Example2: Inject custom structure

To work with custom structures and types, I prefer to write macros like this:

#define NSValueFromPrimitive(primitive) ([NSValue value:&primitive withObjCType:@encode(typeof(primitive))])

Then, injection of structure whould be easy:

Object:

typedef struct {
    int mainNumber;
    int secondNumber;
} Passport;

@interface People : NSObject
@property (nonatomic) Passport passport;
@end

Definition:

- (People *)peopleWithPassport:(NSValue *)passport
{
    return [TyphoonDefinition withClass:[People class] configuration:^(TyphoonDefinition *definition) {
        [definition injectProperty:@selector(passport) with:passport];
    }];
}

Calling:

Passport p;
p.mainNumber = 1234;
p.secondNumber = 5678;
People *people = [factory peopleWithPassport:NSValueFromPrimitive(p)];