레몬 생으로 씹어먹으면 맛있어요. :: NSArray와 NSDictionary에서 배열연산자 사용하기.

글쓴 사람 -페이스북 유저 - : https://www.facebook.com/sic.hhwang


[알고 계십니까]

NSArray와 NSDictionary에는 C의 subscripting operator(쉽게 얘기하면 배열 접근 연산자)를 사용할 수 있습니다.
(지원 컴파일러: Apple LLVM 4.0 이상 또는 LLVM/Clang 3.1 이상)
(지원 SDK: OS X 10.8 이상 및 iOS 6.0 이상)

예제:
NSArray *fibonacci_partial=@[ @1, @1, @2, @3, @5, @8, @13, @21, @34 ];
NSDictionary *pangram_intl=@{
@"English": @"The quick brown fox jumps over the lazy dog",
@"Deutsch": @"Falsches Üben von Xylophonmusik quält jeden größeren Zwerg",
@"한국어": @"야 니들 밥에 쵸코우유 토핑해 먹었쪄"};

NSLog(@"This should be 21: %@", fibonacci_partial[7]); // 21
NSLog(@"한국어: %@", pangram_intl[@"한국어"]); // 야 니들...

뿐만 아니라, NSMutableArray와 NSMutableDictionary는 subscripting operator를 이용한 값 설정도 가능합니다.

NSMutableArray *wrong_fib_part=@[ @1, @1, @2, @3, @5, @8, @13, @181, @34 ];
NSMutableArray *spam_list=@{
@"신한": @"김대리",
@"농협": @"박대리"};

NSLog(@"This should be 21: %@", wrong_fib_part[7]); // 181
wrong_fib_part[7]=@21;
NSLog(@"This should be 21: %@", wrong_fib_part[7]); // 21

NSLog(@"사전: %@", [spam_list description]); // 신한: 김대리, 농협: 박대리
spam_list[@"우리"]=@"한대리";
NSLog(@"사전: %@", [spam_list description]); // 신한: 김대리, 농협: 박대리, 우리: 한대리

잘만 사용한다면 코드 길이를 짧게 줄일 수 있는 강력한 문법입니다.

+덧
위 확장 문법은 각기 다음과 같은 메서드로 치환됩니다:
-[NSArray objectAtIndexedSubscript:]
-[NSDictionary objectForKeyedSubscript:]
-[NSMutableArray setObject:atIndexedSubscript:]
-[NSMutableDictionary setObject:forKeyedSubscript:]



Ardie Hwang 덧붙여, 여러분의 클래스에 저 아래쪽 메서드를 구현한다면 여러분도 동일하게 사용 가능합니다. 다 구현해야 하는 것은 아니고 array-style이냐 dictionary-style이냐에 따라서만 구현하시면 돼요.

'프로그래밍 언어 > Objective-C' 카테고리의 다른 글

Objective-C의 @property와@synthesize.  (0) 2013.02.18
Posted by 레몬사과
,