Deleting in NSMutableArray

2019-07-31 01:45发布

I have an array here, example I have 4 images on each column, each responds to its default index: enter image description here

When an image is deleted for example index 1. as shown in the image below:

enter image description here

The index becomes 0,1,2 :

enter image description here

which I want to be is 0,2,3 (Which is the original array index):

enter image description here

Could anyone help me on how to achieve this?

my code for my array:

self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++) 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"myImages%d.png", i]]; 
    if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){ 
        [images addObject:[UIImage imageWithContentsOfFile:savedImagePath]]; 
    } 
}     

2条回答
smile是对你的礼貌
2楼-- · 2019-07-31 02:25

use an NSMutableDictionary instead

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Item 0" forKey:@"0"];
[dictionary setValue:@"Item 1" forKey:@"1"];
[dictionary setValue:@"Item 2" forKey:@"2"];
[dictionary setValue:@"Item 3" forKey:@"3"];

//    0 = "Item 0";
//    1 = "Item 1";
//    2 = "Item 2";
//    3 = "Item 3";
NSLog(@"%@", dictionary);

//Remove the item 1
[dictionary removeObjectForKey:@"1"];

//    0 = "Item 0";
//     2 = "Item 2";
//    3 = "Item 3";
NSLog(@"%@", dictionary);
查看更多
Animai°情兽
3楼-- · 2019-07-31 02:28

You can put another key in your dictionary which will correspond to the index before any removal of objects. Display it instead of the index and you will get the desired result.

edit 2:

self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++) 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"myImages%d.png", i]]; 
    if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){ 
        NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
        [container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:@"image"];
        [container setObject:[NSNumber numberWithInt:i] forKey:@"index"];
        [images addObject:container];
        [container release]; // if not using ARC 
    } 
}

And when you're getting the corresponding object, you do:

NSDictionary *obj = [images objectAtIndex:someIndex];
UIImage *objImg = [obj objectForKey:@"image"];
int objIndex = [[obj objectForKey:@"index"] intValue];
查看更多
登录 后发表回答