Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Instance variables at runtime

I want to create instance variables dynamically at runtime, and I want to add these variables to a category. The number of the instance variables may change based on the configuration/properties file which I am using for defining them.

Any ideas??

like image 551
Anil Kumar Avatar asked Apr 09 '26 22:04

Anil Kumar


1 Answers

Use Associative References - this is tricky, but that is the mechanism invented specifically for your use case.

Here is an example from the link above: first, you define a reference and add it to your object using objc_setAssociatedObject; then you can retrieve the value back by calling objc_getAssociatedObject.

static char overviewKey;

NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];
NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];

objc_setAssociatedObject (
    array,
    &overviewKey,
    overview,
    OBJC_ASSOCIATION_RETAIN
);
[overview release];

NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
NSLog(@"associatedObject: %@", associatedObject);

objc_setAssociatedObject (
    array,
    &overviewKey,
    nil,
    OBJC_ASSOCIATION_ASSIGN
);
[array release];
like image 134
Sergey Kalinichenko Avatar answered Apr 11 '26 14:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!