从NSMutableArray中删除对象

时间:2018-06-18 15:23:52

标签: nsmutablearray

我在使用" removeObjectAtIndex"时遇到了一些问题。方法是为了在可变数组中删除某些类型的字符串文字,使用以下技术(我在文本编辑器中写了这个): -

  #import <Foundation/Foundation.h>

  @interface Test: NSObject
  @property  NSMutableArray *elements;
  -(void) method;
  @end

  @implementation Test
  @synthesize elements;
  -(void) method{
     elements= [[NSMutableArray alloc] init];
     [elements addObjectsFromArray:@[@"c", @"a", @"b", @"c", @"c", @"d", @"c", @"c", @"e", @"c"]]; 
     NSLog(@"number of elements initially- %d", elements.count);
     int index= elements.count-1;
     for(id i in [elements reverseObjectEnumerator])
     {
        // static int index= elements.count-1;
        NSLog(@"index- %d", index);
        if([i isEqual:@"c"]){
          [elements removeObjectAtIndex:index];
          NSLog(@"Object in place of removed object- %@, at index- %d", [elements objectAtIndex:index], index);
          NSLog(@"No. of elements left after the removal- %d", elements.count);
        }
       index--;
     }  
 }
 @end

 int main()
 {
   Test *test= [[Test alloc] init];
   [test method];
   NSLog(@"elements- %@", test.elements);
 }

在终端中运行它时,我得到一个超出范围的例外。

  cd '~/Desktop/Source Code/'; clang -framework Foundation -w ObjectRemovalInArray.m -o ~/Desktop/Binaries/ObjectRemovalInArray && ~/Desktop/Binaries/ObjectRemovalInArray
  2018-06-18 20:25:25.797 ObjectRemovalInArray[4684:731973] number of elements initially- 10
  2018-06-18 20:25:25.797 ObjectRemovalInArray[4684:731973] index- 9
  2018-06-18 20:25:25.798 ObjectRemovalInArray[4684:731973] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 9 beyond bounds [0 .. 8]'
  *** First throw call stack:
  (
0   CoreFoundation                      0x00007fff345f632b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x00007fff5b764c76 objc_exception_throw + 48
2   CoreFoundation                      0x00007fff34637634 _CFThrowFormattedException + 202
3   CoreFoundation                      0x00007fff34515290 __CFStringDecodeByteStream3 + 0
4   ObjectRemovalInArray                0x00000001007dbbaf -[Test method] + 799
5   ObjectRemovalInArray                0x00000001007dbd54 main + 68
6   libdyld.dylib                       0x00007fff5c37e015 start + 1
7   ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6

基本上,我有点理解这个问题,因为我意识到在循环的开始,我有#34; i&#34; (类型为id)指针指向数组中的最后一个对象,该对象也恰好是要删除的对象。当发生这种情况时,mutable-array会缩小1个内存位置,而第10个(index-9)会因为它被解除分配而无法访问。所以到那时候&#34;我&#34;指针需要将一个点移回下一个对象,但这并不是在引擎盖下发生的。我应该使用最终的哨兵来解决这个问题吗?因为确实尝试使用&#34; nil&#34;把它放在数组的末尾。但它不会接受(void *)对象。我该如何解决?任何帮助对我都有很大帮助。请注意,我只想使用快速枚举来解决问题。  奇怪的是,这个问题在Xcode中并没有出现。我在那里使用了相同的代码片段;构建并运行它作为更大项目的一部分。没问题。没有抛出异常。

0 个答案:

没有答案
相关问题