views:

234

answers:

3

I am pretty new to objective C, I was trying this:

I have NSMutableArray with different objects in it of different classes. Now I want to get the class name & related stuff & also check if the respective object is NSString or not.

How should I go about it..

I was trying something like this it wasn't working ofcourse

for(NSString *string in array){

NSLog(@"Name of the class : %@", [NSString stringWithCString:class_getName(Class id)];

`

+4  A: 

If you're on Mac OS X, you can use [object className], it returns an NSString

for(id obj in array) NSLog(@"Name of the class: %@", [obj className]);

To check if it's a NSString, you should use something like this:

for(id obj in array) {
    if ([obj isKindofClass:[NSString class]]) {
        // do something
    }
}
Zydeco
I am not sure what do you mean by if you are on MAC OS X...?it would work on iPhone right...?you meant it wont work on GNUStep right ....?
Asad Khan
@Asad the `-className` method only exists on Mac. For the same functionality on iPhone, use `NSStringFromClass([obj class])`.
Dave DeLong
You can also obtain the string name of a class using [[obj class] description].
Brad Larson
I would generally advise using NSStringFromClass() even on the Mac, just because -className is *intended* for scripting; not introspection.
Mike Abdullah
+6  A: 
for(id object in array){
    NSLog(@"Name of the class: %@", [object className]);
    NSLog(@"Object is a string: %d", [object isKindOfClass:[NSString class]]);
}

Take a look at the NSObject class and protocol for other interesting methods.

JoostK
+2  A: 

I have NSMutableArray with different objects in it of different classes. Now I want to get the class name & related stuff & also check if the respective object is NSString or not.

Hold up. Why do have an array of different typed objects in the first place? Could you redo your design to avoid getting into that situation?

As others have said, -isKindOfClass: works. One downside is it generally leads to brittle code. Here your loop needs to know about all the classes that could be in the array. Sometimes this is the best you can do though.

Designs that use -respondsToSelector: tend to be a little more robust. Here your loop would need to know about the behaviors it depends on of classes in the array.

harveyswik
+1 for suggesting to use `-respondsToSelector:`, I think that is the way to go in the above example.
stefanB
@harveyswik: actually I am not developing an actual software, I was just trying out cocoa/objective c... I am learning it actually... anyway thanx for the -respondsToSelector: tip
Asad Khan