I want to store instance variable references of aribrary objects in an array, so that I can iterate over the array and set these instance variables.
Would I have to provide their memory addresses to the array? like
[arr addObject:&anIvar];
?
I want to store instance variable references of aribrary objects in an array, so that I can iterate over the array and set these instance variables.
Would I have to provide their memory addresses to the array? like
[arr addObject:&anIvar];
?
Technically speaking, you can get an address of ivar and store it in NSArray by converting it to NSNumber. Still, it would be better to store a pair of values: target object and target property and use KVC to set them:
[myArray addObject:[NSArray arrayWithObjects:self, @"someProperty", nil]];
Acceccible with:
for(NSArray *pairs in myArray) {
[[pairs objectAtIndex:0] setValue:myValue forKey:[pairs objectAtIndex:1]];
}
Edited (The old answer was based on misunderstanding the question.)
The easiest way to get a pointer to an instance variable is to use the get accessor, if it's present. Example:
@interface MyClass : NSObject {
UIView* aView; // Protected by default.
}
@property (nonatomic, retain) UIView* aView;
// Elsewhere in the code..
MyClass* myClass = [self getThatObject];
UIView* viewOfMyClass = myClass.aView;
// You may now do what you wish with viewOfMyClass, which is a reference to
// myClass's aView object, including add it to an array for later use.
You can sometimes grab a pointer to an instance variable by thinking of the object as a struct. Example:
@interface MyClass : NSObject {
@public
UIView* aView;
}
// Later, in another part of the code...
MyClass* myClass = [self getThatObject];
UIView* viewOfMyClass = myClass->aView;
viewOfMyClass.tag = 100; // Just changed myClass's aView's tag.
This works because aView
is a public instance variable in MyClass
.
If the instance variable you want to mess with is protected or private, and there's no accessor, then it's a little harder. If it's your own class, you can just add an accessor.
If it's not your class, then this is a clear sign that you'd be breaking encapsulation if you used such a pointer. So I wouldn't recommend it, but you could still achieve this goal with some clever casting.