How to read resource files in a framework?

I created the cocoa framework and application on Mac OS X. The structure is dynamically linked to the application. In the structure class, I need to read the resource file in this framework resource folder. Code below

NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; NSString *characterCodeTable = [resourcePath stringByAppendingPathComponent:@"pymb.txt"]; 

does not work, since "resourcePath" is the path to the application resource folder, not the framework.

So, how can I access the infrastructure resource folder in the code in this structure?

BTW: Is there any best practice for organizing different files in a framework / application package?

+4
source share
2 answers

Instead of calling +[NSBundle mainBundle] call either +[NSBundle bundleWithIdentifier:] or +[NSBundle bundleForClass:] . The first takes an NSString argument to determine the frame index; the latter accepts the Class argument of the class provided by the framework. You can then call up the usual NSBundle paths as needed.

Full documentation can be found here .

+11
source

When using solutions such as

there are several counters and side effects,
 [NSBundle mainBundle] 

or

 NSBundle *localBundle = [NSBundle bundleForClass:[myObject class]] 

when the structure of the application is similar to

 MyContainerApp |------Frameworks/ |-----------------MyFramework.framwork/ |-------------------Resources/ |-------------mydata.json 

So, if you can create a package file and transfer it to a container application (as a third-party framework developer), you can provide this API

 + (NSBundle *)frameworkBundle { static NSBundle* frameworkBundle = nil; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath]; NSString* frameworkBundlePath = [mainBundlePath stringByAppendingPathComponent:@"YourFrameworkBundle.bundle"]; frameworkBundle = [NSBundle bundleWithPath:frameworkBundlePath]; }); return frameworkBundle; } 

BUT very super-lightweight and let the super-efficient solution be the old C header with hexdump

 xxd -i mydata.json >> mydata.json.h 

This hexdump will generate a header file with these definitions.

 unsigned char mydata_json[] = { // hex array }; 

and

 unsigned int mydata_json_len = 32227; 

So in your structure or static library you can access it simply

  unsigned char *rawBytes = mydata_json; NSUInteger dataLen = mydata_json_len; NSData *serializedData = [NSData dataWithBytesNoCopy:rawBytes length:dataLen freeWhenDone:NO]; 

then you might want to get it into text:

 NSString* myString = [NSString stringWithUTF8String:[rawBytes bytes]]; 

What is it. Happy coding!

+3
source

Source: https://habr.com/ru/post/1490059/


All Articles