Skip to content

wrap primitive values into NSValue

Jasper Blues edited this page Jul 31, 2014 · 7 revisions

To pass primitive values into a TyphoonAssembly method with run-time arguments, 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

Let's say you have an object:

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

and you want to inject the age property as a run-time argument.

Let's prepare definition for that:

- (People *)peopleAged:(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 peopleAged:@23]; //Passed NSNumber will be unwraped into NSUInteger

Example2: Inject custom structure

To work with custom structures and types, we recommend a macro like this:

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

Then, inject the structure as follows:

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)];

Quick Start!

Get started in two minutes.

Main Track

Get familiar with Typhoon.

Advanced Topics

Become a Typhoon expert.

Under the Hood

For contributors or curious folks.

Clone this wiki locally