Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

objective c - Pass a class as a parameter?

I have been lead to believe that it is possible to pass a class as a method parameter, but I'm having trouble implementing the concept. Right now I have something like:

- (id)navControllerFromView:(Class *)viewControllerClass
                          title:(NSString *)title
                      imageName:(NSString *)imageName
{
    viewControllerClass *viewController = [[viewControllerClass alloc] init];
    UINavigationController *thisNavController =
    [[UINavigationController alloc] initWithRootViewController: viewController];

    thisNavController.tabBarItem = [[UITabBarItem alloc]
                                  initWithTitle: title
                                          image: [UIImage imageNamed: imageName]
                                            tag: 3];
    return thisNavController;
}

and I call it like this:

rootNavController = [ self navControllerFromView:RootViewController
    title:@"Contact"
    imageName:@"my_info.png"
];

What's wrong with this picture?

question from:https://stackoverflow.com/questions/1030605/pass-a-class-as-a-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
- (id)navControllerFromView:(Class)viewControllerClass

It's just Class, without the asterisk. (Class isn't a class name; you're not passing a pointer to an instance of the Class class, you're passing the class itself.)

rootNavController = [ self navControllerFromView:RootViewController

You can't pass a bare class name around like this—you have to send it a message. If you actually want to pass the class somewhere, you need to send it the class message. Thus:

rootNavController = [self navControllerFromView:[RootViewController class]
                                          title:@"Contact"
                                      imageName:@"my_info.png"
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...