I’m trying to zip files using the command-line utility through NSTask.
pseudocode:
controller:
init:
register_self_as_observer_of_nstask_notifications
startZip(file):
file = somefileobject
task = "zip" with file path as argument
task.launch
notification_listener(notification):
task = notification.get_object
file = task.???
So how can I find out which file object the notification pertains to? I usually use the userInfo dictionary for such things, but NSTask has no such option. From Apple Dev: This notification does not contain a userInfo dictionary.
Thanks!
Use the associated object API to attach a user info dictionary to the task instance. This would be the cleanest approach, but it cannot be used prior to the introduction of the associated object API with Mac OS X 10.6.
Alternatively, you can use a dictionary that maps from task to user info. Creating a dictionary mapping from task to user info is not as straightforward as it sounds:
[taskInfoDict setObject:userInfo forKey:task]becauseNSTaskdoes not conform toNSCopying, butNSDictionaryrelies on copying its keys.NSNumberas a proxy for the task object mostly works. But process IDs can be reused, and a task doesn’t get a PID till after it’s been launched. The root of the problem is: You don’t control the process ID; the underlying OS does.Using the address of the task object seems to be the best solution:
Assuming a reference-counted environment, the task object’s address will be stable for its lifetime, and its lifetime is entirely under control of your application. A copying garbage collector would throw a wrench in this solution, but in that case, you could use a collection class that can handle the pointer directly (
NSMapTable).