Is it possible to check whether an identifier exists in a storyboard before instantiating the object?

后端 未结 6 1394
-上瘾入骨i
-上瘾入骨i 2021-02-19 06:53

In my code I have this line, but I was wondering if there is way to check whether @\"SomeController\" exists before I use it with the \"instantiateViewControllerWit

6条回答
  •  梦毁少年i
    2021-02-19 07:15

    You can use valueForKey: on UIStoryboards. UIStoryboards have a key called "identifierToNibNameMap", its value is an NSDictionary with the UIViewControllers in that storyboard. This inner NSDictionary uses the viewcontroller's names as keys so you can actually check if a viewcontroller exists in a storyboard with the following code:

    if ([[storyboard valueForKey:@"identifierToNibNameMap"] objectForKey:myViewControllerName]) {
        // the view controller exists, instantiate it here
        UIViewController* myViewController = [storyboard instantiateViewControllerWithIdentifier:myViewControllerName];
    } else {
        //the view controller doesn't exist, do fallback here
    }
    

    Note: Apple has been known to reject apps that query the underlying properties of cocoa classes using valueForKey:. These underlying properties could change at any time in the future, breaking app functionality without warning. There is no deprecation process for these things.

提交回复
热议问题