views:

161

answers:

2

I have an view controller class. I want to do some things in my view when the accelerometer detects movement and calls the accelerometer:didAccelerate: method in the delegate object.

That delegate object is the problem here in my brain. Currently, my brain is freezed and I don't get it what would be better. Let me know what you think!

Solution 1) In my view controller class I conform to the UIAccelerometerDelegate protocol, and implement that accelerometer:didAccelerate: method. In the -applicationDidFinishLaunching: method of my AppDelegate class I set that view controller object up as the delegate for receiving method calls upon accelerations. I think that's not really good.

Solution 2) I create a blank new object called AccelerationDelegate, conform to that UIAccelerometerDelegate protocol, implement that accelerometer:didAccelerate: method and in the -applicationDidFinishLaunching: method of my AppDelegate class I set that view controller object up as the delegate for receiving method calls upon accelerations.

But for solution 2 my brain got stuck a little bit! How would I access the view objects from my view controller inside that object?

The problem here is, that I have more than one view controller around. I use a tab bar controller to switch between them.

Any suggestions how I could get that right?

+2  A: 

I agree that the second method is better. Are you looking to access just the currently selected tab view, or just a specific view in your app.

In any case, what I would do is to set up properties for your UITabViewController in your UIApplicationDelegate so that you can access it from the delegate (you can get the app delegate by calling [[UIApplication sharedApplication] delegate]). For example:

YourApplicationDelegate *appDelegate = (YourApplicationDelegate *)[[UIApplication sharedApplication] delegate];
FirstUIViewController *firstViewController = appDelegate.firstViewController;
[firstViewController doStuff];

where firstViewController is a property on your delegate.

Benny Wong
Thanks. I want to access views (specific: UIImageView objects) inside a UIScrollView.
Thanks
+2  A: 

If your acceleration is specific to one view controller, then it makes sense to have the view controller receive the information necessary to alter its own subviews. However, it might be better to set your view controller to be the delegate when the view appears, and set the delegate to null when it disappears. (Specifically, - (void) viewWillAppear: and - (void) viewWillDisappear:)

Ed Marty
thanks for that disappear hint!
Thanks
Great info on the releasing of the delegate. I didn't even think about that but it's something that I do all the time in the .Net world so I should have. Thanks!
Mike Bethany