我这里有一个数组,例如我在每列上有4个图像,每个图像都响应其默认索引:
删除图像时,例如索引1.如下图所示:
索引变为0,1,2:
我想要的是0,2,3(这是原始数组索引):
有人可以帮我解决这个问题吗?
我的数组代码:
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]];
}
}
答案 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);