Re: Casting from NSArray to a custom class
Re: Casting from NSArray to a custom class
- Subject: Re: Casting from NSArray to a custom class
- From: Guy English <email@hidden>
- Date: Wed, 16 Feb 2005 10:46:10 -0500
Hi,
Short answer:
NSLog( @"%@", theArray ) will tell you what's in the array.
Long winded-waiting-for-compile-to-finish-answer:
I'm afraid it's not really clear what you're after here. C++ casting
tricks don't apply to Objective-C - there is no implicit conversion,
constructors, or operators. Casting works exactly as it does in C. A
fair amount of rambling follows.
As was pointed out before NSArray holds only NSObjects. Not 'Objects'
in an abstract collection of data sense, but objects that are
subclasses of NSObject. So if you're looking to stick anything but
NSObject subclasses in there you're out of luck. One of the nice
things about NSObject subclasses is that you can call "description" on
them and they'll return a string that tells you what class they are
and often (for Apple objects at least) what their data members are.
Another nice thing is that NSArray is itself a subclass of NSObject so
you can call description on that and it'll tell you what it contains.
NSArray *myArray = get_the_array();
NSLog( @"%@", [myArray description] );
Now NSLog is nice and you can actually just do:
NSLog( @"%@", myArray );
And it'll call description for you.
Sticking that in your code will print to the log the contents of the
array. By examining the log you'll be able to work out what kind of
objects you're dealing with. You then can call methods on those
objects. You don't want to go treating then like c structs or c++
objects with public members because it just won't work.
// ok, just for the record here's how to wrap a struct and stick it in an array
// you say that's not what you want but maybe it'll be some help ...
NSMutableArray *theArray;
unsigned max;
unsigined i;
theArray = [[NSMutableArray] alloc] init];
max = number_of_structs();
for ( i = 0; i < max; i++ )
{
NSValue *structWrapper;
structWrapper = [NSValue valueWithBytes: &(ptr_to_struct_by_index(
i )) objCType: @encode( struct mystruct )];
[theArray addObject: structWrapper];
}
// theArray now contains NSValue objects holding each of your structures.
// access your structure with:
struct mystruct theStruct;
[[theArray objectAtIndex: index] getValue: &theStruct];
NSLog( @"struct: %d %d", theStruct.a, theStruct.b );
Guy
_______________________________________________
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