测试特定图像是否已复制到粘贴板

Testing that a particular image was copied to pasteboard

我正在编写一个测试来验证将图像复制到粘贴板的功能。

这是测试,我更愿意这样写:

// reset the paste board
UIPasteboard.generalPasteboard.image = nil; //<-- this explodes
XCTAssertNil(UIPasteboard.generalPasteboard.image);

// Grab some random existing image
UIImage *image = [UIImage imageNamed:@"some-image"];
MJKMyClass *myInstance = [[myInstance alloc] initWithImage:image];
[myInstance doSomethingThatCopiesImageToPasteboard]

XCTAssertNotNil(UIPasteboard.generalPasteboard.image);

这失败了:

failed: caught "NSInvalidArgumentException", "-[UIPasteboard setImage:]: Argument is not an object of type UIImage [(null)]"

这令人惊讶,因为根据 UIPasteboard header,图像是一个可为空的字段。

@interface UIPasteboard(UIPasteboardDataExtensions)
<...>    
@property(nullable,nonatomic,copy) UIImage *image __TVOS_PROHIBITED;
<...>
@end

我认为这意味着他们正在对参数进行运行时检查,即使它可以为空。

我尝试过的事情:

您可以使用 items 属性:

清除粘贴板而无需通过 nil
UIPasteboard.generalPasteboard.items = @[];

或在Swift中:

UIPasteboard.generalPasteboard().items = []

为了比较 UIImage,您可能需要查看其他一些问题: