View Full Version : [Solved] Cocoa pasteboard

May 24, 2009, 09:37 PM

I'm looking for some sample code with method how to make a button which copy a plain text from the text field without selecting it to the clipboard.
What is the best way to do this? Thanks!


May 24, 2009, 10:12 PM
can you call the text field's stringValue method and make a copy of that string and store it somewhere?

May 25, 2009, 09:10 AM
Yep, everything is OK until copying NSMutableString.
With "rooString" pasteboard is filled but when I change it to "Final_String" it's empty.

Below is example:

- (IBAction)generate:(id)sender
NSString* rooString = [NSString stringWithUTF8String: reinterpret_cast<const char*>(joeyString)];
NSMutableString *Final_String = [NSMutableString stringWithString: rooString];

NSInteger i = 47;

for (i=6; i<[Final_String length]; i+=7)
[Final_String insertString:@" " atIndex:i];

[txt_Field_1 setObjectValue: Final_String];


- (IBAction)copy:(id)sender
NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
[pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
[pasteBoard setString:Final_String forType:NSStringPboardType];


May 25, 2009, 10:28 AM
I found solution.


[pasteBoard setString:Final_String forType:NSStringPboardType];


[pasteBoard setString:[txt_Field_1 stringValue] forType:NSStringPboardType];

solved problem.


Thomas Harte
May 26, 2009, 06:55 AM
If it helps, stringWithString returns a string that is a member of the autorelease pool. As a result, it is safe to rely on it being a valid string for the rest of that method, to pass it in function calls from that method or to return it from that method to a direct caller, but it is not otherwise safe to set the pointer aside and use it later in a separate method.

In your case, you have two separate IBActions, so for this purpose they count as completely separate methods. Therefore it is not safe to assume that Final_String will remain valid between generate: and copy:. The solution you have is the best practice for this code, but in general if you want to keep something around you need either to retain it (and release it later) or to create it with an alloc and some sort of init, for example:

Final_String = [[NSMutableString alloc] initWithString:rooString];

Or, more simply:

Final_String = [rooString copy];

Memory allocation and deallocation in Objective-C (at least before the garbage collector, which I've yet to learn about) is overwhelmingly based on following well-defined programming patterns. As a general rule, if you don't explicitly alloc then the thing you get is going to be autoreleased at some point; init-type methods are used on explicitly allocated objects, class methods (ie, those that start with +) other than alloc that return an instance of the class return one that will be autoreleased.