6

I use UIPasteboard to copy/paste text between two UITextView.

Code looks like this:

- (void)viewDidLoad {
   [super viewDidLoad];
   pasteBoard = [UIPasteboard generalPasteboard]; //it is declared in .h as UIPasteboard *pasteBoard;
}

-(IBAction)doCopyBtn {
    if (![toCopyTextView.text isEqualToString:@""]){
        pasteBoard.string = toCopyTextView.text;
        NSLog(@"pasteb1 %@", pasteBoard.string);
    } else {
        NSLog (@"error! enter smth");
    }
}

-(IBAction)doPasteBtn {
    if (![pasteBoard.string isEqualToString:@""]){ 
        toPasteTextView.text = pasteBoard.string;
        NSLog(@"pasteb2 %@", pasteBoard.string);
    } else {
        NSLog (@"error! enter smth");
    }
}

And even this cant help (NSLog returns: pasteb2 (null))

-(void) viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [pasteBoard setString:@""]; 
}
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
Aleksey Potapov
  • 3,683
  • 5
  • 42
  • 65

3 Answers3

23

iOS – UIPasteboard

Try the following:

    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    [pb setValue:@"" forPasteboardType:UIPasteboardNameGeneral];

Arab_Geek's response is correct but available for Cocoa (and I suspect you are looking for an iOS solution)

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Riddick
  • 400
  • 2
  • 9
  • 1
    Thanks for answer. If someone wants an ugly long single line: `[[UIPasteboard generalPasteboard] setValue:@"" forPasteboardType:UIPasteboardNameGeneral];` – Basil Bourque Nov 15 '14 at 06:06
3

OS X - NSPasteboard

Here you go ..

NSPasteboard *pb = [NSPasteboard generalPasteboard];
[pb declareTypes: [NSArray arrayWithObject:NSStringPboardType] owner: self];
[pb setString: @"" forType: NSStringPboardType];
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
AK_
  • 1,879
  • 4
  • 21
  • 30
2

Setting the value to "" will return nil for all intended purposes. It will, however, leave the pasteboard in a slightly different state as before a paste operation.

Swift

let pb = self.pasteBoard()
pb.setValue("", forPasteboardType: UIPasteboardNameGeneral)

...is not equivalent to UIPasteboard.removePasteboardWithName(). If restoring the UIPasteboard state is of concern(1), you can use the following block:

Swift

let pb = self.pasteBoard()

let items:NSMutableArray = NSMutableArray(array: pb.items)
for object in pb.items {
    if let aDictionary = object as? NSDictionary {
        items.removeObject(aDictionary)
    }
}
pb.items = items as [AnyObject]

(1) Restoring state.

SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179