I have many objects reference the same class of stored data. In previous programs, I’ve used singletons, but am trying to abandon that practice and only use them as a last resort when necessary, mainly due to the bad reputation they have (and indeed I’ve abused them in the past).
But I’m wondering just how much of an advantage my new technique is. I’m simply creating weak references to the same set of data so a bunch of classes point to the same memory to pull data as needed. Such as:
@property (nonatomic, assign) MyDataClass*mydata;
In a custom init of the class, I pass a reference as a method parameter, then the property assigns to this reference.
Is this a valid, acceptable way to do things? I’m having trouble finding much of an organizational advantage to doing this over using singletons.
The pattern you use is just fine, eventually this pattern is used in all standard C++ programs without reference counting or other advanced memory management tools. The only thing you have to ensure that your object hierarchy strictly respects the weakness of the reference i.e. the dependency of the object having the reference towards the object that is behind that reference. In other words, you always have to ensure that the owner of the reference is deleted before the reference and you have to do ensure manually since you’re not using the reference counting.
This means more responsibility for you, the programmer as you always have to have total control over the lifetime of your objects. It is quite easy to make mistake with your pattern since you can’t know from the code having the weak reference whether the original object still exist or it is deleted. You have to ensure this with your design pattern.
For this reason I don’t suggest to “mix” the two approaches, i.e. having weak references to an object that might be freed out-of-control by a
retaintype property (when the value of the property changes from your object), anautoreleaseor byARC.Reference counting was introduced to take away this responsibility from the programmer and make it easier to write safe code. Your pattern is fine, it is used by millions of C++ programs but you have to be conscious of your responsibility.