Monday, April 25, 2011

Writing a string to NSPasteBoard

I cannot get this method to return YES:

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}

I have verified that stringToWrite is coming through properly, the method just always returns NO.

Any ideas?

Here is the rest of the class:

@interface ClipBoard : NSObject {
    NSPasteboard *pasteBoard;
}

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite;
- (NSString *) readFromPasteBoard;
@end

@implementation ClipBoard
- (id) init
{
    [super init];
    pasteBoard = [NSPasteboard generalPasteboard];
    return self;
}

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}

- (NSString *) readFromPasteBoard
{
    return [pasteBoard stringForType:NSStringPboardType];
}

@end

From stackoverflow
  • Here is the working version of the method:

    - (BOOL) writeToPasteBoard:(NSString *)stringToWrite
    {
        [pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
        return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
    }
    
    Peter Hosey : You should use nil for object pointers, NULL only for non-object pointers. Using the wrong one misleads the reader (who will be you six months from now).
    macinjosh : Actually this code snippet came from an Apple provided example. I think they would know the right way to do things. But I digress, it is now changed to nil.

0 comments:

Post a Comment