简体   繁体   中英

NSFileManager works when built in Xcode as release, but not when ran as standalone OS X Cocoa app

I have the following function written to randomly pick a file from a directory. It works totally fine when I build the project in Xcode for release with the application that automatically opens. However, if I open the application from finder, pressing the button that triggers this function will cause my program to freeze then crash. The only thing I could think of was changing the argument to contentsOfDirectoryAtPath: to not have the ./, but either version has the same exact issue.

Looking at Console tells me that my program exited abnormally with a Floating Point Exception, but I have no idea what's causing it. Is there something jumping out to you guys that I'm not seeing? I only started learning/using objective-C and cocoa about a week ago, so this is all fairly new to me.

Thanks for taking a look at this...

- (NSMutableString*)setFilePathRandom{
NSArray* files;
NSFileManager* fileManager;
fileManager = [[NSFileManager alloc] init];
files = [fileManager contentsOfDirectoryAtPath:@"./Random Trippy Pics" error:NULL];
NSString* directoryPath = (NSMutableString*)[fileManager currentDirectoryPath];
NSString* fileName;
do{
    fileName = [files objectAtIndex:(arc4random()%[files count])];
}while([fileName isEqualToString:@".DS_Store"]);
filePath = [NSString stringWithFormat:@"%@/Random Trippy Pics/%@",directoryPath,fileName];
[fileManager release];
return filePath;
}

When an OS X application is run from Xcode, its current directory is the path to the build folder. When run "normally", the current directory is / . So your program is looking for a directory at /Random Trippy Pics , which almost certainly doesn't exist. Where is that directory normally?


Edit:

You could get the directory in which the application is currently stored with this bit of code:

NSString *currentStoragePath = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];

However, if the Random Trippy Pics directory is required by the application, you should store it in a known location -- preferably the application's Resource directory. Then you can get the contents with:

NSArray *files = [[NSBundle mainBundle] pathsForResourceOfType:nil inDirectory:@"Random Trippy Pics"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM