سؤال

I have the following method-header in a singleton:

-(int) reconnectToServerForClass:(id)myClass

The parameter myClass is always the self-object of the calling class. Different ViewControllers in my project call this method so my question is this:

Is it possible to access myClass.view or what can I do to achieve that?


my intention is that I want to show a progress-hud for every ViewController that calls the method:

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:myClass.view animated:YES];

Isn't there the need for casting myClass before I can access the view-property?

هل كانت مفيدة؟

المحلول

If I understand correctly you can do the following:

-(int) reconnectToServerForClass:(UIViewController *)myClass
{
    //myClass.view
}

or inside the method

-(int) reconnectToServerForClass:(id)myClass
{
    if([myClass isKindOfClass:[UIViewController class]])
    {
        UIViewController *viewController = myClass; //edit as suggested by Peter Segerblom
        //viewController.view
    }
}

Which ever option you choose is that it will depend on how you use it and how you want to manage or limit the callers, in option 1 the parameter must be a sub class of UIViewController and the same for option 2 but the difference is that you can pass in anything but if the type is not UIViewController it will just do nothing.

Disclaimer: This code is not tested and typed from memory, so it might not compile, let me know if you come across issues and I will edit answer.

نصائح أخرى

Yes.

If you want to access it from the singleton class, you make a member or property of which is a pointer to a view, then set that in reconnectToServerForClass: and access it as you would any other member.

If you want to access it from outside, you do the same, and do something like [[MySingleton instance] view]

Be aware that dragons lie ahead of your path, you will need to make sure that views "unset" this property before they are destroyed, otherwise your singleton might try to access a no-longer-existing view instance.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top