Frage

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:

  1. Is there a way to determine the actual class of the current instance inside the for loop?

  2. Is there a way to differentiate the two object instances in the for declaration?

War es hilfreich?

Lösung 2

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.

Andere Tipps

There is

[obj1 isMemberOfClass: [whateverObj1Is class]];

But that would likely be true for obj2 since it is a subclass

A good solution would be to have a member function called value or something that class 2 would override returning 0 or something along those lines.

You could try something like this:

int total = 0;
for (Obj1 *t in arry1){
    if([t isMemberOfClass:[Obj1 class]]) total += t.value;
}

All objects implement the NSObject protocol. This code uses two methods in that protocol. isMemberOfClass: checks if the object is of the class that is passed as an argument. The class method returns the class object for the receiver’s class.

Source/ more info

Also, if you want to check for objects that are of the Obj1 class or any of its sublasses you can use isKindOfClass: instead.

You could use introspection to determine which class each of the objects in the array belong to. There are two useful methods to determine the class of an object. isKindOfClass: and isMemberOfClass:. isKindOfClass: returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class. Whereas, isMemberOfClass: returns a Boolean value that indicates if the object is a member of that specific class.

You could therefore do this:

int total = 0;
obj1 *myObj1;
for (NSObject *object in arry1)
{
    if([object isMemberOfClass:[obj1 class]])
    { 
        myObj1 = (obj1 *)object;
        total += myObj1.value;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top