我正在尝试将我的应用程序保留在Dock中,但是我无法执行此操作。
我的目标是什么?
@interface UserDefaultsHelper : NSUserDefaults
- (BOOL)addApplicationToDock:(NSString *)path;
- (BOOL)removeApplicationFromDock:(NSString *)name;
@end
@implementation UserDefaultsHelper
- (BOOL)addApplicationToDock:(NSString *)path {
NSDictionary *domain = [self persistentDomainForName:@"com.apple.dock"];
NSArray *apps = [domain objectForKey:@"persistent-apps"];
NSArray *matchingApps = [apps filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K CONTAINS %@", @"tile-data.file-data._CFURLString", path]];
if ([matchingApps count] == 0) {
NSMutableDictionary *newDomain = [domain mutableCopy];
NSMutableArray *newApps = [apps mutableCopy];
NSDictionary *app = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:path, @"_CFURLString", [NSNumber numberWithInt:0], @"_CFURLStringType", nil] forKey:@"file-data"] forKey:@"tile-data"];
[newApps addObject:app];
[newDomain setObject:newApps forKey:@"persistent-apps"];
[self setPersistentDomain:newDomain forName:@"com.apple.dock"];
return [self synchronize];
}
return NO;
}
- (BOOL)removeApplicationFromDock:(NSString *)name {
NSDictionary *domain = [self persistentDomainForName:@"com.apple.dock"];
NSArray *apps = [domain objectForKey:@"persistent-apps"];
NSArray *newApps = [apps filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"not %K CONTAINS %@", @"tile-data.file-data._CFURLString", name]];
if (![apps isEqualToArray:newApps]) {
NSMutableDictionary *newDomain = [domain mutableCopy];
[newDomain setObject:newApps forKey:@"persistent-apps"];
[self setPersistentDomain:newDomain forName:@"com.apple.dock"];
return [self synchronize];
}
return NO;
}
@end
我从这里找到了上面的代码。 Code Source
上面的代码已经编译并运行,但是它将应用程序添加到应用程序的停靠栏中。
我是新手。因为我没有操作系统知识水平,请对我宽容。
非常感谢您的帮助和关注。
答案 0 :(得分:1)
提供的代码是正确的唯一问题是Dock没有刷新。所以我们只需要刷新DOCK
为了刷新停靠点,我从obj-c
调用终端命令 终端命令 killall dock
....code...
[self runCommand:@"killall Dock"];
}
-(NSString*)runCommand:(NSString*)commandToRun;
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command: %@",commandToRun);
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}