我应该使用mutableArray还是mutableDictronary?

时间:2015-04-07 04:59:38

标签: objective-c nsmutablearray nsmutabledictionary

我试图填写muatableArraymutableDictionary。然后我将取出1个对象,比如4,然后我将需要通过从索引中减1来移动4个以上的所有元素。

使用mutableArray removeObjectAtIndex很容易做到这一点。但问题是,我不会在每个索引上添加对象。

这是我的意思的基本布局:

 1. one
 2. two
 3. three
 // 4. (Empty)
 5. five
 6. six
 // 7. (Empty)
 // 8. (Empty)
 9. nine
 10. ten

所以我的问题是,我应该使用mutableaArray,只需将nulls添加到空索引中,如下所示:

for (int i = 0 ; i < [myArray count]; i++)
{
     if (![myArray objectAtIndex:i]) {
         [array addObject:[NSNull null]];
     }
}

或者我应该使用mutableDictionary,当我需要移除一个对象时,我应该像这样手动完成所有操作:

[self.myDict removeObjectForKey:currentKey];
for (NSNumber *key in [[self.myDict allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
  if ([key integerValue] > currentKey) {
    NSNumber *newKey = @([key integerValue]-1);
    self.myDict[newKey] = self.myDict[key];
    [self.myDict removeObjectForKey:key];
  }
}

1 个答案:

答案 0 :(得分:1)

for (int i = 0 ; i < [myArray count]; i++)
{
     if (![myArray objectAtIndex:i]) {
         [array addObject:[NSNull null]];
     }
}

首先,您没有打开所有应该打开的警告。作为证据我认为你使用的是int而不是NSUInteger i。这是一个非常坏的习惯。打开警告是一种非常便宜且有效的查找编程错误的方法。

其次,不要使用!检查指针是否为零。做体面的事情并将其与零比较。你想检查它是否为零,这就是你应该在你的代码中写的东西。以反映您想要做的方式编写代码是避免编程错误的一种非常便宜且有效的方法。

第三,这段代码绝对没有意义。如果我&lt; myArray.count,然后[myArray objectAtIndex:i]不可能是nil。 [myArray objectAtIndex:i]将永远不会返回零。