Question

I would like to get some opinion about best practice in iOS5 and higher (ARC enabled). For example, I have a database with cars - image, name, max speed, etc. info. In app I have to show a car with info, then, after user interaction - next car, then next... without any moving to previous one.

If I have a class Car, then which would be better solution and why?

Solution 1: on the first time to create an instance of Car, using alloc and init and then, every time, when I have to show the next one - just update this instance with new data by changing existing values (speed from 250 to 180, color from black to red, etc.)

Solution 2: every time use alloc and init, allowing ARC to free the memory previously taken and just forgetting about previously allocated objects.

Solution 3: probably there are also other solutions, how to solve this problem - I'm eager to hear them.

Thanks in Advance

Was it helpful?

Solution

If your class is really a Car class, it should represent one car in your database and not be some kind of handler object to show database entries. If you want to do that, you should at least make it a class that is properly named and configured to do that kind of work.

There is nothing wrong with creating a Car instance for every car you read from your database.

OTHER TIPS

Loading the image from disk to memory is probably what will take the longest. So I don't think there would be any significant difference in speed between your solutions.

Memory usage will also be roughly the same. In your first approach, the image and all the other instance variables will be released when you set a new value. In the second approach, the whole Car instance will be released, resulting in the release of all it's instance variables.

From the software design perspective I recommend going with the second solution. A Car instance should represent exactly that, an instance of a car. It would be misleading to have only one instance of it and then change its values all the time. If you want to do something like that, I recommend renaming your class to something like CarManager and have a singleton object or use class methods.

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