Alternative to Casting?


#1

Hi

Would I right in thinking that if didn’t have this line … HipnosisView hV = (HipnosisView)[self view]; //casting
in the -(void)accelerometer: didAccelerate: method,
but instead created a pointer hv to a HypnosisView, in the HypnosisViewController.h as such

#import <Foundation/Foundation.h>
@class HypnosisView;

@interface HypnosisViewController : UIViewController
{
HypnosisView *hv;
}
@property (nonatomic,retain) HypnosisView *hv; // and @synthesize the property in the .m file
@end

that I could have the following code below to achieve the same results ?

-(void)accelerometer:(UIAccelerometer *)meter didAccelerate:(UIAcceleration *)accel
{

[[self hv] setXShift: 10.0 * [accel x]];
[[self hv] setYShift: -10.0 *[accel y]];

//redraw the view

[[self hv] setNeedsDisplay];
}

Thanks

Any info appreciated.

Lenny


#2

That’s pretty close.

However, you want the hypnosisView method to return the view of the view controller. The way you have it set up now, you would be returning another instance of HypnosisView instead of THE view of the view controller.

Here’s what you can do:

  1. Don’t declare a new instance variable.
  2. Declare the property as:
  1. Don’t synthesize hypnosisView
  2. Implement the method declared by this property in the .m as so:

- (HypnosisView *)hypnosisView { return (HypnosisView *)[self view]; }


#3

Thanks for the info Joe


#4

Hi,

I’m a bit confused. Please help. Why does the implementation create another instance of the view?

And what’s the best practice to get a pointer to a particular view?

For example, say in a viewController’s loadView method, a scrollView is declared and a hypnosisView is added as its subview. If I need to update hypnosisView what would be the best way to access it? One way I can think of is to us self.view then return a array of it subviews and get its pointer at index 0 but that sounds like a lot of work just to get a pointer. So I always declare a hypnosisView instance variable and properties in viewController similar to this post but after reading this post it sounds like every time I’m creating a new instance.

HELP!

edit: I guess I’m a bit confused about one viewcontroller having multiple view. I can only assign one of them as THE view and then for all other view manipulation I have to somehow get a pointer from THE view.