What is best for the new NSObject - alloc / init or modify an existing one?

I would like to get some feedback on best practices in iOS5 and above (ARC enabled). For example, I have a database with cars - image, name, maximum speed, etc. Info. In the application, I have to show the car with the information, then, after interacting with the user, the next car, then the next ... without any transition to the previous one.

If I have a Car class, what would be the best solution and why?

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

Solution 2: use alloc and init each time, allowing ARC to free up previously saved memory and just forget about previously allocated objects.

Solution 3: there are probably other solutions how to solve this problem - I really want to hear them.

Thanks at Advance

+4
source share
2 answers

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

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

+4
source

Loading an image from disk into memory is likely to be the longest. Therefore, I do not think that there will be any significant difference in speed between your decisions.

Memory usage will also be approximately the same. In your first approach, the image and all other instance variables will be released when setting a new value. In the second approach, the entire Car instance will be released, as a result of which all instance variables will be released.

In terms of software design, I recommend moving on to the second solution. A car instance should represent just that, a car instance. It would be wrong to have only one instance and then change your values ​​all the time. If you want to do something like this, I recommend renaming your class to something like CarManager and have a singleton object or use class methods.

+2
source

Source: https://habr.com/ru/post/1436148/


All Articles