In the Apple Documentation, it is stated that NSDate objects are immutable which I presume means that once they are initialised with a value, they cannot/shouldn’t be changed.
However, in the following code I need an NSDate to be one of two possible values so naturally i might use:
for (class* object in array) {
if (i == 0) {
NSDate* fromDate = //...a date
} else {
NSDate* fromDate = //...a different date
}
//Use fromDate
i++
}
As far as I’m aware, this is not valid because using fromDate outside the if block is outside of scope.
The solution would normally be:
for (class* object in array) {
NSDate* fromDate = [[NSDate alloc] init];
if (i == 0) {
fromDate = //...a date
} else {
fromDate = //...a different date
}
//Use then release fromDate
i++
}
However, according to the Apple Docs, when an NSDate receives ‘init’ it’s initialised with todays date and since it’s immutable, I can’t reassign it.
What’s the correct thing to do here? Is it simply to copy all of my code into the if blocks twice? Or have I misunderstood the term immutable? Or perhaps I need a retain after the assignment in the first example?
thanks
Your question also reveals a fundamental misunderstanding of how pointers work. Yes, the documentation says that
NSDateobjects are immutable. ButfromDateis not anNSDate. It is anNSDate*. In other words, it is simply a forwarding address that points to where the actualNSDateobject lives. The pointer itself is mutable (unless it’s declared asconst), and you can feel free to change the pointer‘s value as much as you like. However, the thing that the pointer points to (the actualNSDate) is correctly immutable.