In my iPhone project, I have a common “date editing” view which features a UIDatePicker. I would like to use this view to update one NSDate property based on the way it’s called.
The way I thought about achieving that is to have an NSDate property called CurrentlyEditedDate which I set to point to the correct NSDate property I could like to edit. But I don’t know how to do that.
Let’s say I have 2 NSDate properties defined:
@property (nonatomic, retain) NSDate *startDate;
@property (nonatomic, retain) NSDate *endDate;
When I launch my view I would like to do the following:
CurrentlyEditedDate = startDate
Or the following based on the caller:
CurrentlyEditedDate = endDate
So that my view can edit any NSDate object. However I don’t know how to define or assign the CurrentlyEditedDate property. Nor do I know how to set it up from the view to a new NSDate value.
I think actually the best solution here would be to implement a delegate protocol. It looks a little thornier, but it won’t be as fragile as trying to store the variable reference.
Here’s what you need to do:
First, declare the protocol so that other classes know what to implement in order to receive your delegate messages. Also, create a .delegate property so that other objects can tell your date picker that they want to get those messages:
Then when you get a new date from your picker, you just need to check to see if you have a delegate, and that they have implemented your method. If they have, just go ahead and tell them about the new date:
Then, in your class where you want to receive the date info you might do something like this:
I just typed that without compiling, but it should be correct. This may seem like a lot of work, but it will very quickly become second nature, and is a much more robust way to handle these kinds of situations.