Macos 设置NSImageView对象的动画并删除该对象失败?

Macos 设置NSImageView对象的动画并删除该对象失败?,macos,cocoa,animation,core-animation,catransaction,Macos,Cocoa,Animation,Core Animation,Catransaction,我的应用程序情况: 我现在有一个显示动态图片的应用程序。我想捕获它的当前图像并将其保存到光盘中 我的目标: 我正在制作一个动画视觉效果:在顶部添加一个图像视图,然后将其从原始帧设置为动画。最后,动画完成后,从vie层次结构中删除此图像视图 现在问题: 第一次触发动作时,它似乎起作用了。但是当第二次触发它时,图像视图不会设置动画并停留在所有子视图的顶部 视图控制器的代码(带ARC): 首先,这是触发快照的IBAction: - (IBAction)actionSaveSnapshot:(id)

我的应用程序情况:
我现在有一个显示动态图片的应用程序。我想捕获它的当前图像并将其保存到光盘中

我的目标:
我正在制作一个动画视觉效果:在顶部添加一个图像视图,然后将其从原始帧设置为动画。最后,动画完成后,从vie层次结构中删除此图像视图


现在问题:
第一次触发动作时,它似乎起作用了。但是当第二次触发它时,图像视图不会设置动画并停留在所有子视图的顶部


视图控制器的代码(带ARC):

首先,这是触发快照的IBAction:

- (IBAction)actionSaveSnapshot:(id)sender
{
    ...    // Save the image file. This works everytime.

    NSThread *tempThread = [[NSThread alloc] initWithTarget:self
                                                   selector:@selector(threadSimulateScreenCapture:) 
                                                     object:nil];
    if (tempThread)
    {
        [tempThread start];
        tempThread = nil;     // Simply release it 
    }
}
这里是线索:

- (void)threadSimulateScreenCapture:(id)arg
{@autoreleasepool {
    NSImageView __strong *subImageView;
    subImageView = [[NSImageView alloc] init];
    NSRect subRect = [_imageView frame];    // the dynamic image view which I want to snapshot with
    const CGFloat animationTime = 0.4;

    [subImageView setWantsLayer:YES];
    [subImageView setImageScaling:NSImageScaleAxesIndependently];
    [subImageView setImage:[_imageView image]];

    dispatch_async(dispatch_get_main_queue(), ^{
        [CATransaction begin];
        [self.view addSubview:subImageView];
        [subImageView setFrame:subRect];
        [subImageView setNeedsDisplay:YES];
        [CATransaction commit];
    });

    [NSThread sleepForTimeInterval:0.01];
    dispatch_async(dispatch_get_main_queue(), ^{
        [CATransaction begin];
        [CATransaction setAnimationDuration:animationTime];
        [subImageView.layer setFrame:CGRectZero];
        [CATransaction commit];
    });

    [NSThread sleepForTimeInterval:(NSTimeInterval)animationTime];    // wait for end of animation

    dispatch_async(dispatch_get_main_queue(), ^{
        [subImageView removeFromSuperview];
    });

    NSLog(@"SubView Count: %@\n%@", self.view.subviews, subImageView);  // MARK. described below
    subImageView = nil;    // release the image
}} // ENDS: thread and aotureleasepool
每次程序运行到“标记”行并打印子视图数组时,很明显,
子图像视图
不会从superview中删除。每次线程结束时,都会出现一个“已删除线程,未提交CATTransaction…”


我做错了什么?

我可以解决我自己的问题:在使用
[subImageView setFrame:subRect]的行中,插入另一行:
[subImageView.layer setFrame:subRect]

同时,在“addSubview:”方法之前添加另一行:
[self.view setWantsLayer:YES]

这似乎奏效了。但我不知道为什么。为什么我要设置视图和层的框架