在objective-c中更改桌面图片

时间:2010-08-20 18:08:47

标签: objective-c cocoa unix terminal

如何更改cocoa / objective-c中的桌面图片?我尝试过使用默认值但有很多错误。

NSArray *args=[NSArray arrayWithObjects:@"write",@"com.apple.desktop", @"Background", @"'{default = {ImageFilePath = \"~/desktop.jpg\";};}'", nil];

NSTask *deskTask=[[NSTask alloc] init];

[deskTask setArguments: args];

[deskTask setLaunchPath:@"/usr/bin/defaults"];
[deskTask launch];
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.desktop" object:@"BackgroundChanged"];

该命令在终端中成功运行。我不需要任何人告诉我完全该怎么做但我想要一些见解。

编辑:我的操作系统是10.4.11

2 个答案:

答案 0 :(得分:3)

我认为规范的方法是使用系统事件的脚本。 Applescript版本类似于:

tell application "System Events"
    tell current desktop
        set picture to (whatever)
    end tell
end tell

您可以使用Scripting Bridge从Objective-C执行此操作。

答案 1 :(得分:2)

当你在shell中使用波浪形压缩路径时,shell会为你扩展波浪号,所以当你在shell中运行命令时,你将桌面图片路径设置为扩展路径(/ path / to / desktop.jpg)。使用NSTask时没有shell工作,因此您显示的代码将其设置为波浪形压缩路径。很少有人期望这样的道路;它们不会扩展波浪号,因此不起作用。

要使该代码有效,您需要使用NSString对象的相应方法扩展代字号本身,或者通过附加到NSHomeDirectory()返回的路径来构造路径。

也就是说,Chuck建议与System Events交谈是一种更好的实现方法。请注意他的评论告诉你如何在不需要Leopard的情况下做到这一点。