Learn how to use quick enumeration on a copy of NSMutableArray to delete objects.

I diligently studied that you cannot delete objects from NSMutableArraywhen you iterate over objects in it.

Going through [< array_object > copy]instead < array_object >.

However, I have a few unanswered questions that I would like to receive from the Objective-C guru.

  • In this first loop, I expected each of them nextObjectto point to a different memory (i.e., I thought that the array msgDetailwould have a list of pointers, each of which points to an address NSDictionarythat contains a specific index of the array). But all prints %p nextObjectgive the same meaning. Why is this?

    for(NSDictionary *nextObject in msgDetailArray)
    {
    
        NSLog(@"Address = %p, value = %@",&nextObject,nextObject) ;
        //Doing [msgDetailArray removeObject:nextObject] here based on some condition fails
    }
    
  • In the second address cycle, the address nextObject NSDictionaryis different from the one printed in the first cycle.

    for(id nextObject in [msgDetailArray copy])
    {
    
        NSLog(@"In copy Address = %p, value = %@",&nextObject,nextObject) ;
    
        //Doing [msgDetailArray removeObject:nextObject] here based on some condition succeeds and it also removes it from the original array even though I am looping through a copy
    }
    
  • , [msgDetailArray copy], a removeObject:, msgDetailArray. removeObject:? , ? , , , , , , ( 2 , , [msgDetailArray copy], msgDetailArray). , , .

    for(id nextObject in msgDetailArray)
    {
            NSLog(@"Address = %p, value = %@",&nextObject,nextObject) ;
            //test what is left in msgDetailArray.  I see that doing removeObject on [msgDetailArray copy] does remove it from the original too.  How is removeObject working (is it actually contents of dictionary)
    }
    
+4
3

" ". , . .

, . . , . .

, . .

2 , . , . ( , , , , , .)

, , . ( , , . .)

, removeObject, , . " 123 Elm". , removeObjectAtIndex, , .

+2
  • , . .

  • &nextObject - , . - : NSLog(@"%p", nextObject);

  • removeObject: , isEqual:, , , .

, , copy . mutableCopy, .

+2

%p . ?

&nextObject - nextObject, , ; - . nextObject , , , , , void*:

NSLog(@"Address = %p, value = %@", (void*)nextObject, nextObject);

for nextObject NSDictionaries ,

.

[msgDetailArray copy], removeObject, msgDetailArray.

, , . , .

The call [msgDetailArray removeObject:nextObject]works with the original array. If you do not want this effect, save the copy in a variable and delete elements from it instead:

NSMutableArray *mutableCopy = [msgDetailArray mutableCopy];
...
[mutableCopy removeObject:nextObject];

This will not affect the original array. However, you cannot iterate mutableCopyat the same time as removing elements from it.

+2
source

Source: https://habr.com/ru/post/1621525/


All Articles