How to access local files within project

試著忘記壹切 提交于 2019-12-20 10:26:49

问题


I want to add some static files (image, binary, etc...) to my app. I've placed them under a folder named Resources and have added it to my XCode project.

Next, I have those files added to the Copy Bundle Resources in the Build Phases tab in the project settings.

However, I can't seem to refer to them in the right way.

For instance, reading a binary file:

NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:@"data.bin"];
if(![is hasBytesAvailable]) NSLog(@"wrong");

This always fails & prints wrong

I tried a similar approach with NSData initWithContentsOfFile: but this wouldn't even execute. Another attempt was to use [NSBundle mainBundle] but this also didn't execute fully.

I'm new to iOS please help I can access my local files! Any help would be appreciated.

Thank you,


回答1:


You need to ensure that you're accessing the file in the right place. Xcode places your resource files in the application's "application bundle" in the Resources directory. There are many ways to dig 'em out.

A common way is to get the pathname of a file in your bundle:

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: @"data" ofType: @"bin"];

If you have other files in nonstandard places in your bundle, there are variations to pathForResource that let your specify a directory name.

If you want to see the actual location on your hard-drive that the simulator is using so you can inspect it, you can say:

NSLog(@"Main bundle path: %@", mainBundle);
NSLog(@"myFile path: %@", myFile);

Search for the "Bundle Programming Guide" in the Xcode documentation library to get started. :-)




回答2:


Use NSBundle class for that. For Example:

NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"bin"];
NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:path];
...



回答3:


Indeed calling [is open] is needed even though you "initialiseWithFileAtPath". I would think the initialisation would automatically open the file for you, but it doesn't.



来源:https://stackoverflow.com/questions/7776536/how-to-access-local-files-within-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!