Objective c Xcode中的标记问题
我有一个显示9个UIImageView的应用程序,我正在为用户添加删除它们的功能。代码运行良好,除了我在interface builder中使用标记时遇到一些问题。我的代码似乎根据图像在数组中的位置删除了图像视图中的图像。因此,如果我有3个UIImageView,我会将第一个UIImageViews标记设置为1,第二个图像视图的标记设置为2,第三个设置为3。我尝试先删除第三个,但得到错误: 由于未捕获异常NSRangeException而终止应用程序,原因:*'-[\uu NSArrayM removeObjectAtIndex:]:索引3超出边界[0..1]。 这是我正在使用的代码:Objective c Xcode中的标记问题,objective-c,xcode,tags,Objective C,Xcode,Tags,我有一个显示9个UIImageView的应用程序,我正在为用户添加删除它们的功能。代码运行良好,除了我在interface builder中使用标记时遇到一些问题。我的代码似乎根据图像在数组中的位置删除了图像视图中的图像。因此,如果我有3个UIImageView,我会将第一个UIImageViews标记设置为1,第二个图像视图的标记设置为2,第三个设置为3。我尝试先删除第三个,但得到错误: 由于未捕获异常NSRangeException而终止应用程序,原因:*'-[\uu NSArrayM re
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(@"Sender is %@", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:@"Delete"
message:@"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(@"User Clicked Yes. Deleting index %d of %d", alertView.tag, [array count]);
NSLog(@"The tag is %i", alertView.tag);
[self.array removeObjectAtIndex: alertView.tag];
NSLog(@"After deleting item, array count = %d", [array count]);
NSLog(@"Returned view is :%@, in view: %@", [self.view viewWithTag:alertView.tag], self.view);
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}
[self.user setObject:self.array forKey:@"images"];
}
我必须将第一个图像放在数组的0索引中,但我知道不能有0标记,因为它是默认标记。所以,我不知道如何回避这个问题。非常感谢您的帮助,谢谢 我认为作为索引号的静态标记不适用于此,因为即使第一次删除时正确,如果删除的不是最后一个数组元素,标记和数组偏移量的匹配也会改变 最好编写一个方法,逐步遍历数组并返回带有匹配标记的项。或者,如果希望通过标记直接访问,请使用字典并使用标记生成密钥 标记匹配的代码如下所示:
- (UIImageView *)viewForTag:(NSInteger)tag {
UIImageView *found = nil;
for (UIImageView *view in self.array) {
if (tag == view.tag) {
found = view;
break;
}
}
return found;
}
- (void)alertView: (UIAlertView *) alertView clickedButtonAtIndex: (NSInteger) buttonIndex {
// ...
// Replacing: [self.array removeObjectAtIndex: alertView.tag];
UIImageView *view = [self viewForTag:alertView.tag];
if (view) {
[self.array removeObject:view];
}
// ...
}
非常感谢你的回答。逐步遍历数组并返回带有匹配标记的项听起来很完美,但我不知道如何编写该代码。对不起,我对Objective-C还是很陌生。我已经用一个样本更新了答案。不要相信它,因为我只是猜测一些变量是如何定义的。但这应该是一个不错的起点。太棒了,非常感谢!如果我将NSData对象放在数组中而不是直接放在UIImageView中,这个方法会起作用吗?再次感谢!否。NSData对象没有可供您检查的标记属性。如果必须这样做,请阅读NSMutableDictionary以及如何使用键。