Passing a variable that can be updated
This seems like a simple thing, but can't get it to work.
I pass a variable into a UIViewController thourgh a standard property:
[aViewController setProposedDate:proposedWorkLog.entryDate];
which is retained by the controller, and possible changed. I have verified that in the controller, the data is modified.
But, after it is popped off the stack and I look in the c开发者_如何学Goalling view, the data has not been updated. Is there a way to pass this variable and have it retain the new value, or a way to pass back a response from a closing view controller?
Thanks!
If you try to modify a property (entryDate
) behind the owner's (proposedWorkLog
) back, this may come with many side effects like inconsistency and memory mismanagement.
I strongly suggest to go a different route, maybe pass the proposedWorkLog
and call setters for the new property on it.
entryDate
looks like a NSDate which is immutable, so you can't change it; you have to replace it with a new instance which is best done by invoking the correct setter.
You need to pass it by reference. Objects in Objective-C are passed by reference because they (usually) are pointers, but primitives on the other hand, are (usually) not pointers. So you need to pass in a pointer to the primitive by using the address-of operator (&
).
So your code should look like this:
[aViewController setProposedDate:&proposedWorkLog.entryDate];
You then need to change your method prototype to take a pointer to the primitive type (say int *
).
Have a look at the way error handling with NSError
works in Objective-C, it's using this methodology all over the place. http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/
I strongly agree with @Eiko. You should think about it a bit differently. In C++ you can do stuff like void flipTheseTwo(int* x, int* y)
but I'm pretty sure that is bad form for Objective-C (and retain'd memory objects).
Here's my suggestion. Use @property (assign) MYWorklog worklog;
@synthesize worklog = _worklog;
[aViewController setWorklog:proposedWorkLog];
[UINavicationController pushViewController: aViewController animated:YES]; // this syntax might be wrong. Mac is not near me. :(
...
(IBAction) updateProposedDate:(id)sender
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
_worklog.entryDate = [dateFormat dateFromString:[sender stringValue]];
[dateFormat release];
}
精彩评论