I have an array here, example I have 4 images on each column, each responds to its default index:
When an image is deleted for example index 1. as shown in the image below:
The index becomes 0,1,2 :
which I want to be is 0,2,3 (Which is the original array index):
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]];
}
}
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];
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);