Testing that a particular image was copied to pasteboard

╄→尐↘猪︶ㄣ 提交于 2019-12-24 17:57:16

问题


I'm writing a test to verify a feature which copies an image to the pasteboard.

Here's the test, as I would prefer to write it:

// 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);

This fails with:

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

Which is surprising, because, according to the UIPasteboard header, image is a nullable field.

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

I presume this means they are doing a runtime check on the argument, even though it is nullable.

Things I have tried:

  • comparing objects by id doesn't work because UIImage's are copied by the generalPastboard.image (every time you call UIPasteboard.generalPasteboard.image you can a different instance)
  • comparing by PNG representation might work, but seems gnarly.
  • comparing by image size has been my closest bet so far, but also seems roundabout.

回答1:


You can clear the pasteboard without having to pass nil by using the items property:

UIPasteboard.generalPasteboard.items = @[];

Or in Swift:

UIPasteboard.generalPasteboard().items = []

For comparing UIImages, you might want to look at some other questions:

  • How to compare two UIImage objects
  • https://stackoverflow.com/search?q=uiimage+compare


来源:https://stackoverflow.com/questions/36091937/testing-that-a-particular-image-was-copied-to-pasteboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!