How to init object using string name of the class?

Discussion in 'iOS Programming' started by Sergio10, Jan 18, 2010.

  1. Sergio10 macrumors regular

    Joined:
    Oct 3, 2007
    #1
    Hi,
    Here is a code:
    PHP:
            NSStringclassName = @"SomeClass"

            
    UIViewController *viewController = [[(Class)className allocinitWithNibName:aXIBName bundle:[NSBundle mainBundle]];    
    It crashes. How to solve the problem?

    Thank you.
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Use NSClassFromString to turn your string into a Class then you can alloc init as usual:

    Code:
    NSString* className = @"SomeClass" 
    
    id myInstance = [[NSClassFromString(className) alloc] init];
    
     

Share This Page