开发者

Objective-C: NSClassFromString() use with navigation controller?

开发者 https://www.devze.com 2023-03-30 05:36 出处:网络
I am wanting to use NSClassFromString() to pass a string to so that will be determining what class is pushed onto the nav controller.Problem is, I am wanting to pass a value to this class, which cause

I am wanting to use NSClassFromString() to pass a string to so that will be determining what class is pushed onto the nav controller. Problem is, I am wanting to pass a value to this class, which causes an error, as well as trying to push the view controller causes an error since NSObject is not a UIViewController type class.

Class screenClass = NSClassFromString(screen.name);
NSObject* newClass = [[screenClass alloc] init];
newClass.asset = asset; // Causes errors because asset not in NSObject
[self.navigationController 开发者_如何学编程pushViewController:newClass animated:YES];// newClass is an NSObject
[newClass release];

Is there a better way to do what I am trying here?


You could simply do

UIViewController *newObject = (UIViewController *)[[screenClass alloc] init];

Then the warnings will be removed.


You can't use dot notation if you can't statically type the variable. If all all of the possible classes descend from one common class that declares the method, you can statically type it as that class. Otherwise, you'll need to use the accessor method for the asset property:

Class screenClass = NSClassFromString(screen.name);
id newClass = [[screenClass alloc] init]; // note that it's an id to indicate that we don't know what it'll be more specifically than an object
[newClass setAsset:asset];
[self.navigationController pushViewController:newClass animated:YES];
[newClass release];

This assumes that the setter for the asset property is setAsset: (which it normally will be).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号