Question

I have a setting for external editor that end-user can change in settings. As I want to make my software smart, I want to set button that starts this external software to disabled state, if software is not valid (maybe TextEdit has been moved to Utilities or somewhere else or something else goes wrong, anything can happen, right?)..

// Default setting: /Applications/TextEdit.app

[[NSWorkspace sharedWorkspace] launchApplication: [[NSUserDefaults standardUserDefaults] stringForKey: @"externalapp"]];

I could just make a simple test that location is valid and exists, but for some reason I decided to go the fancy way and came to think that there should be a test that tests this for a proper application - it doesn't need to test it for TextEdit.app - because the whole idea is that you can use nearly any editor you want-- That's why it is customizable in the first place -- but I just want a simple check that we won't encounter problems that could had been avoided by this test.

And yes, I know I should use TextEdit.app to open a file, but I am not in that phase yet, so there isn't anything produced for opening yet, I'll do that later-- in this phase this is enough to see that the idea works and I can do some testing.. But I am listening if someone wants to share good ideas that I maybe haven't yet thought about with this.

Was it helpful?

Solution

This is how to do the test I was asking for..

NSString *fileType = [sharedWorkspace typeOfFile: [[NSUserDefaults standardUserDefaults] stringForKey: @"externalapp"] error:nil];

if (( UTTypeEqual((CFStringRef)fileType, kUTTypeApplication) ) || ( UTTypeEqual((CFStringRef)fileType, kUTTypeApplicationBundle) ) || ( UTTypeEqual((CFStringRef)fileType, kUTTypeApplicationFile) ))
    NSLog(@"Yes - File type is equal to Application");

Here is a proper transformer implementation:

@implementation icalValidTransformer

+ (Class)transformedValueClass { return [NSNumber class]; }
+ (BOOL)allowsReverseTransformation { return NO; }

- (id)transformedValue:(id)value {  
    if (( value == nil ) || ( [[NSApp delegate]sharedWorkspace] == nil ))
        return [NSNumber numberWithBool: NO];

    NSError *fileError = nil;
    NSString *fileType = [[[NSApp delegate] sharedWorkspace] typeOfFile:value error: &fileError];

    if ( fileError != nil )
        return [NSNumber numberWithBool: NO];

    if (( UTTypeEqual((CFStringRef)fileType, kUTTypeApplication) ) || ( UTTypeEqual((CFStringRef)fileType, kUTTypeApplicationBundle) ) || ( UTTypeEqual((CFStringRef)fileType, kUTTypeApplicationFile) ))
        return [NSNumber numberWithBool: YES];

    return [NSNumber numberWithBool: NO];
}

@end

It is also a very nice example of how to use fileError with -typeOfFile - if there is an error (for example, file does not exist) this disabled button/menu/whatever control you were using..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top