I’m working on an iPhone tweak where I need to read from and modify the contents of a struct. However, the struct definition is different between iOS 4.1, iOS 4.2, and iOS 5, and I would like to retain compatibility with all of these. The problem is not that I can’t do it; the problem is that it doesn’t make sense to me to have to rewrite 100+ completely-identical lines of code for each iOS update that happens to change the struct.
Rather than get too involved by actually posting the source from project without any context, I wrote up a simplified example problem. It is a bit too lengthy to include in this post, so I placed it on Pastie here: http://pastie.org/3295629 All the details of the problem are included as comments in that Pastie.
Thanks in advance for any help you might have. I’m totally stumped.
(If you want to see the actual structs I’m dealing with in the iOS project: http://pastie.org/3296564)
Sounds like you should hide access to the struct behind an interface. The 100+ lines piece of code you’re talking about shouldn’t use the real struct directly, but the interface.
eg if the two different versions are like:
You wrap an interface around this that has:
The
get_foo()andset_foo()copy between the original struct into your interface struct and back respectively. The version field is set to either 1 or 2, so the code using this struct can decide what fields to use.This example uses a copy of the struct. This is simple and works for simple structures (like file information). You could also design an interface struct that uses pointers instead of copied values, like:
These are just examples, there are a million ways to make abstractions in C.