Question

Is there a way to change the value of a NSDate without creating a new instance of NSDate? I'd like to keep the pointer the same and just replace the underlying data.

First idea was to sublass NSDate and adding a property that keeps the NSDate value...

Was it helpful?

Solution

I understand the reasoning, yet I think the idea of a mutable subclass is dangerous:

The problem is that frameworks don't expect NSDate instances to change. Thus, they don't copy them where they would in case of NSString or other classes conforming to NSMutableCopying.

Also, NSDate probably implements copy by just retaining the same instance and returning it. You'd have to override this behavior which, again, might be unexpected.

The idea of an NSDate (similar to NSNumber) is to represent an immutable value. It's difficult to imagine how and where the frameworks rely on that fact.

OTHER TIPS

An alternative would be to wrap NSDate into your own class. Your class will the have a pointer to an internal NSDate object. You can then change this internal object, but doing so will leave your wrapper object pointer unchanged.

You'd have to implement methods to get and set the internal date form this wrapper, but that's not to difficult.

If you have a NSMutableArray or similar container class then you can add NSNull objects instead and replace them later. It should then be possible to serialize it. The NSNull object is a singleton so this reduces the memory consumption until being replaced. Cheers :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top