I have an array, arry1
that holds two kinds of objects obj1
and obj2
. obj2
is a subclass of obj1
. I wrote a method to sum the value
of all occurances of obj1
which includes:
int total = 0;
for (obj1 *t in arry1){
total += t.value;
}
The problem is it totals both obj1
and obj2
items. It does the same if I change the for loop to be obj2 *t
. So I have two questions:
Is there a way to determine the actual class of the current instance inside the for loop?
Is there a way to differentiate the two object instances in the for declaration?
You have to check each object and only add its value if is is of obj1
class.
int total = 0;
for (obj1 *t in arry1) {
if ([t class] == [obj1 class])
total += t.value;
}
Please note that it common to start class names with a capital letter. Also Obj1
would be a misleading name as it implies instance, not class.