自定义数据
要被粘贴板使用,一个对象必须符合NSPasteboardWriting
和/或NSPasteboardReading
协议。你可以使用自定义对象或包含自定义数据的NSPasteboardItem
。
概述
任何放入粘贴板的对象必须符合NSPasteboardWriting
协议; 要从粘贴板取回对象的实例,它必须符合NSPasteboardReading
协议。一些常用Foundation和Application Kit类都实现了这两个协议,包括NSString, NSImage, NSURL, NSColor, NSAttributedString, and NSPasteboardItem
。
If you want to be able to write your custom object to a pasteboard, or initialize an instance of your custom class from a pasteboard, your class must also adopt the corresponding protocol. In some situations, it may be appropriate to use NSPasteboardItem.
Custom Class
对于下面的例子,
@interface Bookmark : NSObject
<NSCoding, NSPasteboardWriting, NSPasteboardReading>
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *notes;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, retain) NSURL *url;
@property (nonatomic, retain) NSColor *color;
@end
Notice that the class adopts the NSCoding protocol so that it can be archived and unarchived.
Writing
NSPasteboardWriting协议
@protocol NSPasteboardWriting <NSObject>
@required
- (NSArray *)writableTypesForPasteboard:(NSPasteboard *)pasteboard;
@optional
- (NSPasteboardWritingOptions)writingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard;
@required
- (id)pasteboardPropertyListForType:(NSString *)type;
@end
第一个方法:
- (NSArray *)writableTypesForPasteboard:(NSPasteboard *)pasteboard
This method returns an array of UTIs for the data types your object can write to the pasteboard.
The order in the array is the order in which the types should be added to the pasteboard—this is important as only the first type is written initially, the others are provided lazily (see Promised Data).
The method provides the pasteboard argument so that you can return different arrays for different pasteboards. You might, for example, put different data types on the dragging pasteboard than you do on the general pasteboard, or you might put on the same data types but in a different order. You might add to the dragging pasteboard a special representation that indicates the indexes of items being dragged so that they can be reordered.
第二个方法:
-(NSPasteboardWritingOptions)writingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard
This method is optional. It returns the options for writing data of a type to a pasteboard.
The only option currently supported is “promised”. You can use this if you want to customize the behavior—for example, to ensure that one particular type is only promised.
第三个方法:
- (id)pasteboardPropertyListForType:(NSString *)type
This method returns the appropriate property list object representation of your object for the specified type.