0

I have an object that is used between all my viewControllers so I have stuck it inside the application delegate. (I assume this is the correct place?).

If an action inside a viewController fires that needs to send something to said object I am performing the following:

- (IBAction)sliderMoved:(id) sender{
    MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [[delegate myObject] setSpeed:(int)slider];
  //  [delegate release];
}

I am a bit concerned I am not releasing the delegate object anywhere, is this ok? If I remove the commented line [delegate release] it just crashes the application.

skaffman
  • 398,947
  • 96
  • 818
  • 769
user649716
  • 109
  • 13

1 Answers1

4

You don't own the delegate object that you create in this snippet. You haven't created it with alloc, new, or a copy. Nor have you retained it. So, it is not your responsibility to release it.

As for putting an object in the Application delegate just to be able to access it from other parts of your code - that is poor OOP design IMO.

Edited to add

I suppose I had better give an example

Suppose you have a class MyClass that you want to create an object of that you can pass around.

You create it in the Application delegate, which it seems you are already doing:

MyObject *myObject = [[MyObject alloc] init];

Then you create another view controller - which you would normally do, except that this view controller has a property:

@property(retain) MyObject *object;

And then you set this property when you create the view controller:

YourViewController *vc = [[YourViewController alloc] init];
vc.object = myObject;

And, if you pass this object to other view controllers as you require.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • Thank you. Where should I store this object? (I am new to iphone and MVC). I need to initialize one object of this class that multiple viewControllers can interact with. – user649716 Nov 19 '11 at 12:16
  • 1
    The way I do it is to create a property for this object in each of the view controllers that use it, and then set it from other controllers. – Abizern Nov 19 '11 at 12:18
  • I'm a bit confused. I thought properties created an object and set up accessor methods for it. How would this initialize one object that can be shared between viewControllers? Sorry for all the questions. – user649716 Nov 19 '11 at 12:24
  • Ignore my previous comment, I believe I have solved it :) For anyone else interested look here http://stackoverflow.com/questions/1123920/how-do-i-shared-an-object-between-uiviewcontrollers-on-iphone – user649716 Nov 19 '11 at 12:31