Re: Check the class of a variable?
Re: Check the class of a variable?
- Subject: Re: Check the class of a variable?
- From: James Bucanek <email@hidden>
- Date: Thu, 6 Apr 2006 08:05:06 -0700
Charlton Wilbur wrote on Thursday, April 6, 2006:
>
>On Apr 6, 2006, at 9:24 AM, d2kagw wrote:
>
>> Hey there all..
>>
>> Just wondering if theres a easy way of checking the class of a
>> variable...
>> I've gotten this far:
>>
>> if ( [[theChildren objectForKey:@"data"] class] == @"NSCFArray" )
>> {
>> // do something
>> }
>
>Look for documentation for +class and -isKindOfClass:. You want
>something like:
>
> if ([[theChildren objectForKey: @"data"] isKindOfClass: [NSArray
>class]])
>
>(It's also a bad idea to refer to classes that aren't explicilty
>documented and public. Apple could change the implementation of
>NSArray in 10.4.7 so that it doesn't use NSCFArray, or so that it
>uses NSCFArray differently. Relying on undocumented behavior *will*
>burn you sooner or later, and when it does, it will be painful.)
As an aside, you *may* have difficulty testing for class membership for primitives like NSArray or NSString. Many of these core classes are implemented as class clusters in the Cocoa framework, so even if you call [NSString stringWithBlah:...] you are not guaranteed to get back a subclass of NSString -- even if the returned object acts, smells, and quacks exactly like an NSString.
As an example, you cannot use isKindOfClass or isMemberOfClass to distinguish betweeen an NSArray and an NSMutableArray (search the Cocoa-Dev archives for the threads), even though the documentation would have you believe that NSMutableArray is a simple subclass of NSArray.
Classes that you define and those that are documented as being subclasses of other classes should respond to isKindOfClass and isMemberOfClass as expected. But just be careful of class clusters and Cocoa classes that are "toll-free bridges" to foundation types. These are often implemented in non-intuative ways.
--
James Bucanek
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden