How can I create a class with only methods of the class that can remember values? How does Core Animation do?
I have some useful methods for physics calculations like acceleration / deceleration, speed and a few more.
Most of them require at least two measurements in time. So every time I want to use them, I have to implement a bunch of instance variables in my object that needs computation, for example to compute acceleration.
For example, wherever I calculate acceleration, I include SLPhysics.h and write in my code:
double acceleration = [SLPhysics + calculateAccelerationForFirstMeasuredSpeed:v1 secondMeasuredSpeed:v2 firstMeasuredTime:t1 secondMeasuredTime:t2];
This works great. But I would prefer a way that behaves like Core Animation, where most of the details for doing what needs to be done are hidden from the user of the class.
So, to prevent the instance variables from remembering the last measured values ββof v1 and t1, I would prefer a simple call like this:
double acceleration = [SLPhysics + calculateAccelerationForMeasuredSpeed:v measuredTime:t context:self];
Pay attention to the context parameter. I think that's the way to go. But at the moment I'm not very clear on how these class methods can access a data structure like NSMutableDictionary. If I were making instance variables, the class method would not have access. If I do it with an instance method, the usage is ugly and hard to read and the user is worried about memory management and other things. Also all this allocation and initialization can cost too much (I think). I mean ... look at Core Animation. It is so simple! I want the same for this. But they also had this problem I think. They need to remember something. Animation duration, context, etc.
I was thinking about writing the values ββto a file, but it is too expensive. I could use SQLite. Probably too expensive operations. These methods can be used in places where 5 to 100 calculations per second are required. Arent has things like "class variables"?
a source to share
Use a singleton. Your class keeps all class variables as singleton. Implement singleton as a method of class static:
@interface SLPhysics {
int a;
int b;
}
+(SLPhysics*)getSingleton;
+calculate;
@end
@implementation SLPhysics
+(SLPhysics*)getSigleton {
static SLPhysics* singleton;
if (null == singleton) singleton = [[SLPhysics alloc] init];
return singleton;
}
+calculate {
SLPhysics* singleton = [SLPhysics getSingleton];
// use singleton.a singleton.b here
}
@end
Add thread safety as needed.
a source to share