Re: fetching from NSArray
Re: fetching from NSArray
- Subject: Re: fetching from NSArray
- From: Sherm Pendley <email@hidden>
- Date: Tue, 2 Oct 2007 21:24:11 -0400
On Oct 2, 2007, at 7:58 PM, Ricky Sharp wrote:
On Oct 2, 2007, at 6:39 PM, Andy Lee wrote:
On Oct 2, 2007, at 7:17 PM, Charles Steinman wrote:
I'm not at a computer where I can test it, but I
assume it's a standard C array:
Oh, that would make sense. For some reason the first thing I
thought of was that the id* was to return a single id by
reference, in which case it would have made more sense to simply
return it by value. But returning a C array makes sense by
analogy to NSString's -getCharacters:range:. The documentation
should therefore be similar IMO.
That's definitely a strange API:
The strange output is the result of using it incorrectly. :-(
NSArray* theArray = [NSArray arrayWithObjects:@"a", @"b", @"c",
@"d", @"e", nil];
NSLog (@"theArray = %@", theArray);
id p = calloc (2, sizeof (id));
Id is a pointer to a single object. To allocate an array of them on
the heap, you'd:
id* p = calloc(2, sizeof(id));
Or, to allocate it on the stack:
id p[2];
[theArray getObjects:&p range:NSMakeRange (1, 2)];
Now, since p is already either an id* or an id[], which amount to the
same thing, you don't need to take its address:
[theArray getObjects:p range:NSMakeRange (1, 2)];
NSString* theFirstString = (NSString*) p;
p += sizeof (id);
NSString* theSecondString = (NSString*) p;
Playing around with pointer arithmetic only serves to confuse the
issue - it would be much clearer to use a simple array subscript.
With that in mind, here's a working example:
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *theArray = [NSArray arrayWithObjects:@"a", @"b", @"c",
@"d", @"e", nil];
NSLog (@"theArray = %@", theArray);
// id *p = calloc(2, sizeof(id));
id p[2];
[theArray getObjects:p range:NSMakeRange (1, 2)];
NSLog (@"theFirstString = %@", p[0]);
NSLog (@"theSecondString = %@", p[1]);
[pool release];
return 0;
}
And its output:
2007-10-02 21:22:04.507 testme[24706] theArray = (a, b, c, d, e)
2007-10-02 21:22:04.507 testme[24706] theFirstString = b
2007-10-02 21:22:04.507 testme[24706] theSecondString = c
sherm--
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden