tags:

views:

20

answers:

1

Hey, i am new to objective C, but i tried to use HOM in order to iterate over an NSArray and append a string to each element.

here is my code:

void print( NSArray *array ) {
    NSEnumerator *enumerator = [array objectEnumerator];
    id obj;

    while ( nil!=(obj = [enumerator nextObject]) ) {
        printf( "%s\n", [[obj description] cString] );
    }
}


int main( int argc, const char *argv[] ) {
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

 NSArray *names = [[NSArray alloc] init];
 NSArray *names_concat = [[NSArray alloc] init];
 names = [NSArray arrayWithObjects:@"John",@"Mary",@"Bob",nil];
 names_concat = [[names collect] stringByAppendingString: @" Doe"];

 print(names_concat);
 [pool release];
}

What is wrong with this code?

My compiler (gcc) says NSArray may not respond to "-collect"

A: 

Because the method -collect is not part of the standard Objective-C library!

You need to get some library and add it to your project to start with. See an article at CocoaDev. For collect, see this blog article.

Starting from 10.6, Apple added some methods to NSArray which accepts blocks (or in other words closures). See NSArray documentation and look for words block.

By the way, on a rather unrelated point, please don't use the method cString. This is deprecated! See NSString documentation. cString is very bad concerning the encoding of the characters. I know you're only using it for a debug purposes, but I don't want you to make it a habit to use deprecated methods in general, and especially about methods concerning encodings.

OS X is in general a OS very friendly to many encodings, but as an East Asian I saw many great programs behaving badly just because the programmers used cString etc... Everything works as long as you use non-deprecated methods. Sorry for putting an unrelated comment :p

Yuji