-1
removeObjectForKey를 사용하여 요소를 제거한 Mutable Dictionary가 있습니다. 괜찮습니다. 그러나 사전을 통해 열거하면 삭제 한 요소의 '구멍'이 있습니다. 따라서 사전을 인쇄 할 때 해당 요소가 (null)로 표시됩니다.NSMutableDictionary에서 nil 항목을 제거하는 방법
요소를 제거한 후 사전을 '포장'할 방법이 있습니까? 열쇠에 연속적인 숫자가 필요합니다. 예 :
전에 삭제 :
key:1 value:red
key:2 value:green
key:3 value:blue
key:4 value:yellow
myDictionary removeObjectForKey:2
현재 : 원함
key:1 value:red
key:3 value:blue
key:4 value:yellow
:
key:1 value:red
key:**2** value:blue
key:**3** value:yellow
코드 NSMutableDictionary
에서 전무 항목을 제거합니다. 이것은 내가 무엇을 최대 온이지만, 그것은 작동하지 않습니다 :
NSDictionary
(및 변경 가능한 서브 클래스) 해시 /지도/연관 배열 같은 역할을하기 때문에 발생
int count = dictFaves.count;
int x = 1; // Dictionaries are 1-relative
while (x <= count) {
// get the current row
NSString *curRow = [NSString stringWithFormat:@"%d", x];
NSString *temp = [dictFaves objectForKey:curRow];
// is this row empty? if so, we have found our hole to plug
if (temp == nil) {
// copy the Fave from the 'next' row to the 'current' row. Effectively
// shifting it 1 lower in the Dictionary
NSString *nextRow = [NSString stringWithFormat:@"%d", x + 1];
temp = [dictFaves objectForKey:nextRow];
[dictFaves setObject:temp forKey:[NSNumber numberWithInt:x]];
// one final thing to cleanup: remove the old 'next' row.
// It has been moved up 1 slot (along with all others)
[dictFaves removeObjectForKey:[NSString stringWithFormat:@"%d", x+1]];
}
x = x + 1;
}
NSMutableArray로 변경하기에는 너무 멀다고 생각됩니다. 불쌍한 계획. 인덱스가 연속적으로 실행될 필요가 없습니다. 항목을 제거하여 만든 사전에서 구멍을 제거 할 수 있으면 행복 할 것입니다. 이 일을하기 위해 위의 코드를 추가했지만 작동하지 않습니다 ... – Bassman
@Bassman : 어떤 구멍에 대해 이야기하고 있습니까? 나는 "구멍"이 "숫자가 연속적이지 않다"고 말하는 방식이라고 생각했습니다. – Chuck
가변 배열을 사용하지 않으려면 사전을 반복하고 필요에 맞게 키를 수동으로 설정해야합니다. – Alexander