Dynamic Loading

发布时间:2014-10-23 23:25:54

Dynamic loading enables an Objective-C program to load both executable code and resources, as they are needed, instead of having to load all program components at application startup. The executable code (which is linked prior to loading) can contain new classes that become integrated into the runtime image of the program. This lazy-loading of program code and resources improves overall performance by placing lower memory demands on the system. This also enhances program extensibility because new software can be added dynamically without change to an existing program. Apple provides the bundle mechanism to support the dynamic loading of software on the iOS and OS X platforms. A bundle is a software delivery mechanism. It consists of a directory with a standardized hierarchical structure that holds executable code and the resources used by that code. A bundle can contain executable code, images, sound files, or any other type of code or resource. It also contains a runtime configuration file called the information property list (Info.plist). Bundles define the basic structure for organizing the code and resources associated with your software; they come in several types: Application bundle: An application bundle manages the code and resources associated with a process (e.g., a program).Framework bundle: A framework bundle manages a dynamic shared library and its associated resources, such as header files. Applications can link against one or more frameworks, for example the Foundation Framework.Loadable bundle: A loadable bundle (also referred to as a plug-in) is a type of bundle that an application can use to load custom code dynamically. The Foundation Framework NSBundle class can be used to manage bundles. An NSBundle object represents a location in the file system that groups code and resources that can be used in a program. Listing 7-13 uses an NSBundle object to dynamically load the path of an application’s information property list named Info.plist. Listing 7-13.  Dynamically Loading a Property List File NSBundle *bundle = [NSBundle mainBundle]; NSString *bundlePath = [bundle pathForResource:@"Info" ofType:@"plist"]; As mentioned, bundles can be used to dynamically load executable code. Listing 7-14 uses anNSBundle object to dynamically load a framework bundle and then create an instance of a class from the framework. Listing 7-14.  Dynamically Loading a Framework Object NSBundle *testBundle = [NSBundle bundleWithPath:@"/Test.bundle"]; id tester = [[[bundle classNamed:@"Tester"] alloc] init];