As other answerers have noted, with the new array syntax you can quite easily construct an array with all your objects in it, but it will keep the old values even if you subsequently change the values of the original ivars. That may or may not be what you are after.
If you are hell-bent on keeping your variables as single objects (as opposed to arrays,) then you can use key-value coding to access them programmatically. Key-value coding is also known as KVC.
The method that does it is valueForKey:
and can be used both on self
and other objects.
MyClass *obj = ... // A reference to the object whose variables you want to access
for (int i = 1; i <= 3; i++) {
NSString *varName = [NSString stringWithFormat: @"var%d", i];
// Instead of id, use the real type of your variables
id value = [obj valueForKey: varName];
// Do what you need with your value
}
There is more about KVC in the docs.
In the interest of completeness, the reason this direct access works, is because a standard KVC compliant object inherits a class method called accessInstanceVariablesDirectly
. If you don't want to support this direct access, then you should override accessInstanceVariablesDirectly
so it returns NO
.