问题
I am now creating cocoapod library. If I want to load json,png and other xib files, I need to use [NSBundle bundleForClass:[self class]]]
instead of using main bundle. I wanted to know is this recommend way to do like this and what does that mean?
回答1:
Apple uses bundles to represent apps, frameworks, plug-ins, and many other specific types of content. Bundles organize their contained resources into well-defined subdirectories, and bundle structures vary depending on the platform and the type of the bundle.
-[NSBundle bundleForClass:]
gives you the bundle for a given class.
For example:
AwesomeApp:
AppController
FrameworkA:
FrameController
Calling in the AppController -[NSBundle bundleForClass:[self class]]
would return the AwesomeApp.app bundle. And within FrameController
it would return the FrameworkA.framework
-
回答2:
Bundles are a fundamental technology in macOS and iOS that are used to encapsulate code and resources. Bundles simplify the developer experience by providing known locations for needed resources while alleviating the need to create compound binary files. Instead, bundles use directories and files to provide a more natural type of organization—one that can also be modified easily both during development and after deployment.
An Xcode Project can contain multiple Targets, which itself may contain different files (e.g. asset files or some sources/configs etc.).
This way you don't have to pack ALL files in ALL targets, but can differentiate. In particular for testing this is a great approach, because you can provide certain testing files/resources/"invalid" files to test your code. Because you do test most of the time code that is in your mainBundle (basically your application, that will be provided) but use also assets or other stuff that shall not be packet within your application.
If you want to (and you probably will stumble over this!) make use of this functionality, you will want to load a certain file from a different bundle.
So, you wont be able to use
[[NSBundle mainBundle] pathForResource:@"tests" ofType:@"plist"]
But will use IN your XCTTestCase-Class in your Tests bundle:
// https://developer.apple.com/reference/foundation/bundle
[[NSBundle bundleForClass:self.class] pathForResource:@"tests" ofType:@"plist"]
https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html
If you really want to know more about Bundles, see this link: https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i
They are very powerful and useful, so take your time :-)
来源:https://stackoverflow.com/questions/43754075/nsbundle-bundleforclassself-class-what-does-that-mean