tags:

views:

31

answers:

2

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

?

+1  A: 

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]];
}
Farcaller
KVC is nice, but could I also have references to instance variables directly in the array?
HelloMoon
Farcaller
A: 

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.

Tyler
That's not really what I'm looking for. I want to store references to instance variables of any objects in an array, so that I can just iterate over all of them and set their values to something (I'll know what kind of value can be assigned).
HelloMoon
Aha! I just realized the misunderstanding.I think you want pointers to variables that are members of a class, probably from outside the class. I was confused because those are called in "member varables" in C++ land, where I grew up; and I'm just seeing now that "instance variables" means the same thing in Objective-C kingdom, or so it seems
Tyler