'removeObjectforKey'에 해당되는 글 1건

  1. 2011.09.30 [아이폰] NSMutableDictionary
개발도구/아이폰2011.09.30 13:36


을 검색하는 가운데 API을 글거 붙여 넣어 봣습니다.

An NSDictionary is immutable. If you need a dictionary which you can change, then you should use NSMutableDictionary.

NSMutableDictionary is a subclass of NSDictionary, so that you can do with an NSMutableDictionary everything which you can do with a simple NSDictionary plus, you can modify it.

To set the value of a key in a dictionary, you can use -setObject:forKey:. If the key is not yet in the dictionary, it is added with the given value. If the key is already in the dictionary, its previous value is removed from the dictionary (which has the important side-effect that it is sent a -release message), and the new one is is put in its place (the new one receives a -retain message when it is added, as usual). You should note that, while values are retained, keys are instead copied.

So, if you use a NSMutableDictionary, you can create our usual dictionary as follows:

NSMutableDictionary *dict;

dict = [NSMutableDictionary new];
[dict setObject: @"/opt/picture.png"        
         forKey: @"Luca"]; 
[dict setObject: @"/home/nico/birthday.png" 
         forKey: @"Birthday Photo"];
[dict setObject: @"/home/nico/birthday.png" 
         forKey: @"Birthday Image"];
[dict setObject: @"/home/marghe/pic.jpg"    
         forKey: @"My Sister"];

To remove a key and its associated value, you can just use the method -removeObjectForKey::

[dict removeObjectforKey: @"Luca"];

추가와 삭제 모두 할수 있지만, 제가 삭제는 해봤는데 참 어렵더군요.
삭제는 된거 같은데 보면 null 이 들어가 있던가 아님 아에 안되던가,
그래서 아에 초기화 하고 다시 집어 넣는방법도 아주 좋으니 고려해 보세요.

사용예는 아래와 같습니다.

1. NSMutableDictionary 생성 및 add 방법

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 

//item add

[dictionary setObject:@"A Book about the Letter A" forKey:@"A"];

[dictionary setObject:@"A Book about the Letter B" forKey:@"B"];

[dictionary setObject:@"A Book about the Letter C" forKey:@"C"];

2. NSMutableDictionary remove 방법
// 전체 루프를 돌면서 각각의 아이템 삭제 작업을 해줘야합니다
 for (id theKey in dictionary ) {
        item = [[dictionary objectForKey:theKey] retain];
        [item removeFromSuperview];
        [item release];
        item = nil;
    [dictionary removeAllObjects];
[ dictionary release];
Posted by 예배하는 프로그래머