Skip to content

Instantly share code, notes, and snippets.

@hachinobu
Last active August 29, 2015 14:19
Show Gist options
  • Save hachinobu/68dc0ace95256ffc3c75 to your computer and use it in GitHub Desktop.
Save hachinobu/68dc0ace95256ffc3c75 to your computer and use it in GitHub Desktop.
クラス名を文字列に

Objective-C

 
+ (UIViewController*)viewControllerForStoryboardName:(NSString*)storyboardName class:(id)class
{
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    NSString* className = nil;
    
    if ([class isKindOfClass:[NSString class]])
        className = [NSString stringWithFormat:@"%@", class];
    else
        className = [NSString stringWithFormat:@"%s", class_getName([class class])];
    
    UIViewController* viewController = [storyboard instantiateViewControllerWithIdentifier:[NSString stringWithFormat:@"%@", className]];
    return viewController;
}
 

Swift

 
    class func viewControllerForStoryboardName(storyboardName: String, klass: AnyObject) -> UIViewController {
        
        let storyboard: UIStoryboard = UIStoryboard(name: storyboardName, bundle: nil)
        var className: String? = nil
        
        if klass is String {
            className = klass as? String
        }
        else {
            //AnyObjectをAnyClassに変換
            let clazz: AnyClass = object_getClass(klass)
            className = NSStringFromClass(clazz).componentsSeparatedByString(".").last! as String
        }
        
        let viewController: UIViewController = storyboard.instantiateViewControllerWithIdentifier(className!) as! UIViewController
        return viewController
    }
    
@hachinobu
Copy link
Author

これでもクラス名取れるっぽい

NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last! as String

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment