views:

115

answers:

1

Hi,

Im learning how to do drag and drop to allow ordering of items in an NSOutlineView. (Its my first time using NSPasteboard).

From the slightly related examples I found online, it seems you use:

[pasteboard setData: data forType: @"myapptype"];

What should be put into the NSData when you are doing a move. The samples put an archived version of the object as the data.

The object attributes could possibly change while the item is being dragged, so doest it make sense that instead I stuff a pointer to the object in there?

+2  A: 

No, you generally don't want to stuff a pointer to an object onto the pasteboard.

The pasteboard has to have (basically) one of two types of things on it: data, or a promise to provide the data when asked for it. The pasteboard's lifetime is potentially (and likely) far longer than the lifetime of your application. So imagine this scenario:

  • User copies some data. You put a pointer to your object on the drag.
  • User quits your program. Your object is deallocated.
  • User starts up another instance of your program and hits paste.

Likely outcome: you crash when the second instance of your program dereferences an invalid pointer.

What data actually needs to go on the pasteboard can be very specific to your program, but you generally speaking don't want to put 'live' data on there. It's in your best interests to archive. You may find NSCoder useful for doing simple archiving.

I will carve an exception here and say one could conceive of doing pointer stuff if it was only ever done for drag and drop (since I don't think you can do the drag without the program still running) and if you cleared the drag pasteboard when you quit the program. But it's not a best practice, and I would say that if you're not very experienced and very aware of the pitfalls, it's a risky technique.

peterb
Thanks for the pointers! I realise their are lots of pitfalls that (I could probably try to avoid with or without success). The compromise could be to give each object a unique identifier in string form. And store the pointer reference in the controller. When an objects dropped I can check the string against the internally stored pointer for accuracy.Thanks!
Jacob
That sounds a lot safer (and should be very easy to encode).
peterb