开发者

How to access local files within project

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,


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. :-)


Use NSBundle class for that. For Example:

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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜