在NSMutableArray中删除

时间:2012-06-26 08:37:18

标签: ios iphone xcode nsmutablearray

我这里有一个数组,例如我在每列上有4个图像,每个图像都响应其默认索引: enter image description here

删除图像时,例如索引1.如下图所示:

enter image description here

索引变为0,1,2:

enter image description here

我想要的是0,2,3(这是原始数组索引):

enter image description here

有人可以帮我解决这个问题吗?

我的数组代码:

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 个答案:

答案 0 :(得分:2)

您可以在字典中添加另一个键,该键在删除对象之前与索引相对应。显示它而不是索引,您将获得所需的结果。

编辑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 
    } 
}

当你得到相应的对象时,你会这样做:

NSDictionary *obj = [images objectAtIndex:someIndex];
UIImage *objImg = [obj objectForKey:@"image"];
int objIndex = [[obj objectForKey:@"index"] intValue];

答案 1 :(得分:1)

使用NSMutableDictionary代替

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);