Monday, April 29, 2013

NSBundle classNamed example ios


classNamed:

Returns the Class object for the specified name.
- (Class)classNamed:(NSString *)className
Parameters
className
The name of a class.
Return Value of [NSBundle classNamed]
The Class object for className. Returns nil if className is not one of the classes associated with the receiver or if there is an error loading the executable code containing the class implementation.
Discussion of [NSBundle classNamed]
If the bundle’s executable code is not yet loaded, this method dynamically loads it into memory. Classes (and categories) are loaded from just one file within the bundle directory; this code file has the same name as the directory, but without the extension (“.bundle”, “.app”, “.framework”). As a side effect of code loading, the receiver postsNSBundleDidLoadNotification after all classes and categories have been loaded; see“Notifications” for details.
Example of [NSBundle classNamed]
- (void) loadPlugin {

    id bundle = [NSBundle bundleWithPath:@"the path you/placed/yourPlugin.bundle"];

    NSLog(@"%@", [[bundle infoDictionary] valueForKey:@"CFBundleDisplayName"]);
    // Here you can preview your plugins names without loading them if you don't need to or just to
    // display it to GUI, etc

    NSError *err;
    if(![bundle loadAndReturnError:&err]) {
        // err 
    } else {
        // bundle loaded
        Class PluginClass = [bundle principalClass]; // here is where you need your principal class!
        // OR...
        //Class someClass = [bundle classNamed:@"KillerAppController"];

        id instance = [[PluginClass alloc] init];

        NSLog(@"%@", [instance stringMessage]);

        [instance release];  // If required
    [bundle unload]; // If required
}