[Objective C] 14 NSArray

프로그래밍/iPhone Dev 2009. 11. 13. 15:36 Posted by galad
Foundation framework classes
The Foundation framework is similar to C++'s Standard Template Library. Although since Objective-C has real dynamic types, the horrible cludge that is C++'s templating is not necessary. This framework contains collections, networking, threading, and much more.

NSArray

main.m
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSEnumerator.h>
#import <stdio.h>

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

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

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *arr = [[NSArray alloc] initWithObjects: @"Me", @"Myself", @"I", nil];
    NSMutableArray *mutable = [[NSMutableArray alloc] init];

    // enumerate over items
    printf( "----static array\n" );
    print( arr );

    // add stuff
    [mutable addObject: @"One"];
    [mutable addObject: @"Two"];
    [mutable addObjectsFromArray: arr];
    [mutable addObject: @"Three"];

    // print em
    printf( "----mutable array\n" );
    print( mutable );

    // sort then print
    printf( "----sorted mutable array\n" );
    [mutable sortUsingSelector: @selector( caseInsensitiveCompare: )];
    print( mutable );
   
    // free memory
    [arr release];
    [mutable release];
    [pool release];

    system("PAUSE");
    return 0;
}


결과
----static array
Me
Myself
I
----mutable array
One
Two
Me
Myself
I
Three
----sorted mutable array
I
Me
Myself
One
Three
Two
계속하려면 아무 키나 누르십시오 . . .

- There are two kinds of arrays (and of usually most data oriented Foundation classes) NSArray and NSMutableArray. As the name suggests, Mutable is changable, NSArray then is not. This means you can make an NSArray but once you have you can't change the length.
  NSArray는 길이 변경 불가.
- You initialize an array via the constructor using Obj, Obj, Obj, ..., nil. The nil is an ending delimiter.
  nil이 끝을 의미. 반드시 필요하겠군..
- In the print method, I used the method description. This is similar to Java's toString. It returns an NSString representation of an object.
  description 메소드가 NSString을 반환하고, cString이 그 내용을 반환.
- NSEnumerator is similar to Java's enumerator system. The reason why while ( obj = [array objectEnumerator] ) works is because objectEnumerator returns nil on the last object. Since in C nil is usually 0, this is the same as false.
  ( ( obj = [array objectEnumerator] ) != nil ) might be preferable.

'프로그래밍 > iPhone Dev' 카테고리의 다른 글

[Objective C] Category  (0) 2009.11.18
[Objective C] 15 NSDictionary  (0) 2009.11.13
[Objective C] 13 Autorelease Pool  (1) 2009.11.13
[Objective C] 12 Dealloc  (1) 2009.11.12
[Objective C] 11 Retain and Release  (0) 2009.11.12