Search code examples
objective-cios5automatic-ref-countingnsobjectalloc

What is best practice for new NSObject - alloc / init or change existing?


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


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.