principalClass
Returns the receiver’s principal class.
- (Class)principalClass
Return Value of [NSBundle principalClass]
The receiver’s principal class—after ensuring that the code containing the definition of that class is dynamically loaded. If the receiver encounters errors in loading or if it can’t find the executable code file in the bundle directory, returns
nil
.Discussion of [NSBundle principalClass]
The principal class typically controls all the other classes in the bundle; it should mediate between those classes and classes external to the bundle. Classes (and categories) are loaded from just one file within the bundle directory.
NSBundle
obtains the name of the code file to load from the dictionary returned from infoDictionary
, using “NSExecutable
” as the key. The bundle determines its principal class in one of two ways:[NSBundle principalClass]- It first looks in its own information dictionary, which extracts the information encoded in the bundle’s property list (
Info.plist
).NSBundle
obtains the principal class from the dictionary using the keyNSPrincipalClass
. For non-loadable bundles (applications and frameworks), if the principal class is not specified in the property list, the method returnsnil
. - If the principal class is not specified in the information dictionary,
NSBundle
identifies the first class loaded as the principal class. When several classes are linked into a dynamically loadable file, the default principal class is the first one listed on theld
command line. In the following example, Reporter would be the principal class:[NSBundle principalClass]
ld -o myBundle -r Reporter.o NotePad.o QueryList.o |
The order of classes in Xcode’s project browser is the order in which they will be linked. To designate the principal class, control-drag the file containing its implementation to the top of the list.
As a side effect of code loading, the receiver posts
NSBundleDidLoadNotification
after all classes and categories have been loaded; see “Notifications” for details.
Example of [NSBundle principalClass]
The following method obtains a bundle by specifying its path (
bundleWithPath:
), then loads the bundle with principalClass
and uses the returned class object to allocate and initialize an instance of that class:- (void)loadBundle:(id)sender |
{ |
Class exampleClass; |
id newInstance; |
NSString *path = @"/tmp/Projects/BundleExample/BundleExample.bundle"; |
NSBundle *bundleToLoad = [NSBundle bundleWithPath:path]; |
if (exampleClass = [bundleToLoad principalClass]) { |
newInstance = [[exampleClass alloc] init]; |
[newInstance doSomething]; |
} |
} |