我有一个绘图板应用程序,我试图通过创建一个可变数组来创建一个撤销按钮,该数组将保存触摸开始时创建的图像的保存路径。这是我到目前为止的代码
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
t++;
mainImages = [[NSMutableArray alloc] init];
NSString *imagePath = [NSString stringWithFormat:@"Documents/imagePath%d.png", t];
savePath = [NSHomeDirectory() stringByAppendingPathComponent:imagePath];
[UIImagePNGRepresentation(_mainImage.image) writeToFile:savePath atomically:YES];
[mainImages addObject:savePath];
NSLog(@"t is: %d", t);
NSLog(@"imagePath is: %@", imagePath);
NSLog(@"savePath is: %@", savePath);
NSLog(@"contents of mainImages is: %@", mainImages);
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
lastPoint = [touch locationInView:self.view];
UIGraphicsBeginImageContext(self.view.frame.size);
}
当我运行它时,似乎我的新路径没有添加到Mutable数组,但是它替换了先前保存的路径。这是我的调试控制台读取的内容:
2014-05-06 14:12:20.550 drawingSkills[6709:60b] t is: 1
2014-05-06 14:12:20.553 drawingSkills[6709:60b] imagePath is: Documents/imagePath1.png
2014-05-06 14:12:20.555 drawingSkills[6709:60b] savePath is: /var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath1.png
2014-05-06 14:12:20.557 drawingSkills[6709:60b] contents of mainImages is: (
"/var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath1.png"
)
2014-05-06 14:12:25.482 drawingSkills[6709:60b] t is: 2
2014-05-06 14:12:25.483 drawingSkills[6709:60b] imagePath is: Documents/imagePath2.png
2014-05-06 14:12:25.485 drawingSkills[6709:60b] savePath is: /var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath2.png
2014-05-06 14:12:25.487 drawingSkills[6709:60b] contents of mainImages is: (
"/var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath2.png"
)
2014-05-06 14:19:42.799 drawingSkills[6709:60b] t is: 3
2014-05-06 14:19:42.800 drawingSkills[6709:60b] imagePath is: Documents/imagePath3.png
2014-05-06 14:19:42.802 drawingSkills[6709:60b] savePath is: /var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath3.png
2014-05-06 14:19:42.804 drawingSkills[6709:60b] contents of mainImages is: (
"/var/mobile/Applications/9D3013C2-F275-486C-B1EF-8DAE9A5BEA91/Documents/imagePath3.png"
)
有谁能告诉我如何添加可变数组的路径而不是替换以前的路径?
谢谢。
答案 0 :(得分:1)
每次调用touchesBegan:withEvent:
时,代码中的以下行都会创建一个新数组,覆盖以前创建的数组:
mainImages = [[NSMutableArray alloc] init];
因此,数组永远不会有多个条目。您必须更改代码,以便只分配一次数组。我建议您将上面的行移到自定义视图类的初始值设定项中(通常为initWithFrame:
)。
如果您绝对必须在touchesBegan:withEvent:
内分配数组,请尝试以下相当粗略的解决方案:
static bool mainImagesAlreadyAllocated = false;
if (! mainImagesAlreadyAllocated)
{
mainImages = [[NSMutableArray alloc] init];
mainImagesAlreadyAllocated = true;
}