NSMutableArray 索引混淆
Posted
技术标签:
【中文标题】NSMutableArray 索引混淆【英文标题】:NSMutableArray index mixed up 【发布时间】:2012-06-26 14:22:08 【问题描述】:我目前正在尝试 iCarousel
Multiple Carousel
示例。
在我的数组中,我使用 NSMutableDictionary 添加了图像:
我有两个:(myImages 和 myImages2 用于我在 ViewDidLoad 中加载的轮播中的两个插槽)
self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedPath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"myImages%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedPath])
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedPath] forKey:@"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:@"index"];
[images addObject:container];
[container release]; // if not using ARC
在我的 iCarousel 中:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
if (carousel == carousel1)
NSDictionary *obj = [items1 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:@"items1"]];
view.tag = index;
else
NSDictionary *obj = [items2 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:@"items2"]];
view.tag = index;
return view;
在另一个视图中,这些数组也被加载,用户有机会选择一个图像进行比较,
当用户选择一个图像时,一个与其标签等效的 int 被传递到我的两个 Carousel 所在的位置。
我是这样比较它们的:
NSInteger image = [prefs integerForKey:@"image"];
NSInteger image1 = [prefs integerForKey:@"image2"];
if (image == [(UIImageView*)[self.carousel1 currentItemView] tag] || image2= [(UIImageView*)[self.carousel2 currentItemView] tag] || )
我这样删除索引:
NSInteger index = carousel1.currentItemIndex;
[carousel1 removeItemAtIndex:index animated:YES];
[items1 removeObjectAtIndex:index];
我想我把它删错了,因为索引没有更新,我想要的是保持它的索引不要像这里的图像一样调整:
Deleting in NSMutableArray
【问题讨论】:
看这个帖子和你的其他帖子,我看不出问题。在标准动态数组中,当一个项目被删除时,所有其他项目的索引都会更新。在这种情况下,您永远不会遇到从列表 0、1、2、3 中删除项目 1 并最终得到 0、2、3 的情况。正确的结果数组是 0、1、2!!!跨度> 但是我在比较挑选的 imageView(tagged view) 和 carouselVIew 时确实遇到了问题,所以我认为我的数组有问题,我真的不知道如何修复它。 这真的是你的代码吗,因为你有一个额外的|| (或)在你的比较结束时 同一比较中的“首选项”是什么? NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];抱歉不完整 【参考方案1】:如果我了解您现在要做什么,即移动两个轮播直到中间一个匹配,然后不让索引简单地消失,那么您可以而不是从数组中删除项目,使用 nil 图像(或具有您选择的支持的有效图像)填充您要删除的位置,并使用标签说明它已经匹配。
这当然取决于我对你想要什么的理解是否有效。
【讨论】:
不是中间,而是用户从另一个视图中选择了图像/索引。喜欢用户选择然后删除。你说的零图像是什么意思?怎么样? 如果设置为 nil,UIImageView 将不显示任何内容,或者在您的其他帖子中,您有蓝色背景,您可以有一个简单的图像,只有蓝色背景(与您的背景相同)所以分配给所有已删除的图像。 另外,用户在看到轮播之前如何选择要从轮播中删除的图像?您说他们应该从另一个视图中选择图像。同样,仍然试图更好地理解你想要完成的事情!!! 我的轮播中的图像来自我的相机胶卷,我将其保存在文档目录中,然后将其加载到另一个视图(如设置视图)中,然后用户将选择要匹配的对象,然后在carousel 视图,carousel 会做一个旋转效果/shuffle 效果,然后比较两者是否与用户选择的相同,如果不继续旋转则停止。以上是关于NSMutableArray 索引混淆的主要内容,如果未能解决你的问题,请参考以下文章
需要在 NSMutableArray 的特定索引处添加文本字段内容