开发者

Checking the presence of a file in the bundle

开发者 https://www.devze.com 2023-02-21 20:52 出处:网络
How can we check if a file is present in the external bundle loaded in the app or not before fetc开发者_运维知识库hing it?To check if a file exists in the bundle, use the NSBundle class.

How can we check if a file is present in the external bundle loaded in the app or not before fetc开发者_运维知识库hing it?


To check if a file exists in the bundle, use the NSBundle class.

NSString *path = [[NSBundle mainBundle] 
                            pathForResource:@"somefileinbundle" 
                            ofType:@"png"];
if (!path)
   NSLog(@"Unable to find file in bundle");

Having said that however, it's typically a bad idea to check if a file exists first before trying to load it. According to the Apple docs on NSFileManager fileExistsAtPath:

Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Avoiding Race Conditions and Insecure File Operations” in Secure Coding Guide


If you only want to know if it's there so you can decide whether to load it or not, I'd just attempt to load it and check if the object returned is nil. If it is, you know it doesnt exist in the bundle.

0

精彩评论

暂无评论...
验证码 换一张
取 消