简体   繁体   中英

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM