views:

67

answers:

3

I am inside a class on a view-based app, one that was creating with one view controller.

WHen I am inside the view controller I can access its view using self.view, but how do I access the same view if I am inside a class?

[[UIApplication sharedApplication] delegate]... //??? what do I put here?

thanks

A: 

Assuming that the view controller is a member of your application delegate. you can access it like this: ("YourAppDelegate" should be replaced with the actual type name of your application delegate)

( ( YourAppDelegate *) [ [ UIApplication sharedApplication ] delegate ] ).viewController.view;

Jacob Relkin
Yes the view controller is a member of the delegate but this code of yours is giving me the message "request for member view in something not a structure or union"... another question is: can I have this line in a generic way? I mean, without having to specify the app name? I ask this because this line is to be used on a method inside a singleton that is used by several apps... and I think these parenthesis you put are not using the proper syntax. thanks.
Digital Robot
This will work without an explicit cast, although the compiler will give you a warning.That error means that the view controller's view does not exist.
Jacob Relkin
Dot notation won't work without an explicit cast in this case - unlike with normal Obj-C message sending syntax, the compiler _needs_ to know that a class responds to a particular message if you use dot-syntax, otherwise it assumes you are attempting to access the member of a struct or union. You could however use the following without a cast (and get a compiler warning, which is bad, so you shouldn't do it in production code):`[[[[UIApplication sharedApplication] delegate] viewController] view];`
Nick Forge
+1  A: 

If you're trying to give a singleton a reference to your main viewController, a better solution might be to get your MyAppDelegate to set a viewController property on your singleton at launch:

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    [MySingletonClass sharedSingleton].viewController = self.viewController;
}

If you plan on re-using a Singleton like this in multiple projects, it often makes more sense to set these sort of properties from your AppDelegate.

Nick Forge
A: 

A subview really shouldn't be manipulating a parent view, each class should manage it's own view.

Anyway, if your class is a subclass of UIView and is a subview of the viewController, you can get the viewController's view by accessing the superview property to get your parent view.

progrmr