Best method to store data for an iOS app? [closed] - ios

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I would like to develop a stock/item inventory app as I progress through learning swift. It would basically be something that has, Item Name, Quantity, and Location.
eg.
Lightbulbs, 25, Work Van
Switches, 6, Warehouse
When the user inputs this data and presses a button, whats the best method of storing this data and retrieving it later. I know I could append this to an array and display the array, but what if the app closes?
Should I be looking at learning database storage? Can I save data to the phone?

whats the best method of storing this data and retrieving it later.
The best method will depend on a bunch of factors, like:
How many records do you want to save?
Do you need to sync this data with a server?
How much does performance matter?
How much do you know about storing data using Swift and iOS?
How likely is it that the data you want to save will change?
The answers to all of those questions are likely to change over time, as you learn more and make more progress on the app and perhaps come to understand the users' needs more. So the best method for saving data is to build something that will let you easily change or even replace the data storage system without requiring changes through the rest of the app.
In other words, you need to define an interface for your data storage needs. The interface is like a fence, with the actual data storage on one side, and the rest of the app (user interface, networking, etc.) on the other.
Having a clear interface to your data storage system will let you get your app up and running quickly with the simplest data storage system that could possibly work. You can store your data as an array of dictionaries, for example, write it all out to a property list using the Array method write(to:atomically:), and read it back using init(contentsOf:). So far, you've only described a need for a single kind of record, with each record having only a few fields. Storing the data in an array and writing it to a property list will work fine for hundreds, maybe thousands of entries; you'll likely have you rethink your user interface before you have a real need to rewrite your data storage system, because nobody likes to scroll through a list of hundreds of items.
As your app evolves and you discover that you don't want to keep all the data into memory at once, or you'd like to ship some data with the app and keep that separate from the data the user enters, or you'd like to speed up your data storage, you can write a new data storage system that conforms to the same interface. Then you can swap the new system in without affecting the rest of the app. So you can switch up to using something fancy like Core Data, or you can implement server-based storage, without having to rewrite big chunks of your app.
Creating a clear interface for your data storage system will also make it easy to write a set of unit tests that ensure that your data storage system does exactly what it's supposed to do and doesn't break. And having a set of unit tests will make it easy to ensure that a future version of your data storage system is as correct as the one it replaces.
Some others here have suggested using Core Data. Core Data is great, but using it is a lot more complicated than just reading your data from a file and writing it back when you're done. The difference between using an array to store your data and using Core Data to do it is very like the difference between a text file and a relational database. Core Data is an object graph manager: it can store many of different types of objects and the relationships between them, and it can store many thousands of all those objects and access them very quickly. When you start to keep track of images of the items in the inventory, the suppliers each of the items comes from, the customers who buy the items, the prices the items are bought and sold for, etc., Core Data will really simplify the task of managing all that data. But trying to learn and use Core Data now, while your needs are very simple, and while you're also trying to learn a new language, will slow you way down without any real benefit. Remember the KISS principle and start simple, but in a way that makes it easy to evolve.

If the data you want to store is very little and not sensitive, you can use UserDefaults
For example, user's name, their age etc.
For Large amounts of data you should use Core Data, its a good and an easy way to manage your objects. For example, you have 1000 items, each with a property, you can basically use core data for that. It is pretty straightforward as how to create Managed Objects, store them and how to later retrieve them using queries.
Basically when you configure your project with core data, project creates an sqlite file attached to your project.
There are many tutorials on how to get started with Core Data, if you have an average experience with iOS, it will be a piece of cake for ya.
Here's a nice tutorial that will help you setup core data in your project:
https://www.raywenderlich.com/173972/getting-started-with-core-data-tutorial-2

You can use either of the methods below depending on your exact requirement.
Core data: You can find a tutorial here.
Using a SQLite DB: You can find a tutorial here.
If it is simple and does not require to store a lot of information, then you can even use the file system to store data. Even PLists are possible.

For a single user who just logs in then you can store it in UserDefaults. But if you have to manage a list of users then use Core Data.

There is a huge difference between these two. SQLite is a database itself like we have MS SQL Server.
However CoreData is an ORM (Object Relational Model) which creates a layer between the database and the UI. It speeds-up the process of interaction as we dont have to write queries, just work with the ORM and let ORM handles the backend. For save or retrieval of large data, I recommend to use Core Data because of its abilities to handle the less processing speed of device.
As a result:
SQLite:
Have Data Constrains feature.
Operates on data, stored on disk.
Can Drop table and Edit data without loading them in memory.
Slow as compared to core data.
You can use SQL for complex data structure
Core Data:
Don't have Data Constraints,if required need to implement by business
logic.
Operates on in memory.(data needs to be loaded from disk to memory)
Need to load entire data if we need to drop table or update.
Fast in terms of record creation.(saving them may be time consuming)
No sql for this. Just load data to array and use in that array.
In my opinion; IF you need several data which settings of your app, or user authentication info or similar works use CoreData
If you have big data to storage, you need to select one of many data records use SQLLite.
Hope It helps.

Related

Core Data for preloaded information

im learning about core data at the moment, I can see its benefits for apps like a phonebook etc, however is core data good if your app is to contain preloaded data. For example the players of an American football team. I was using MESASqlite and manually entering the ino and then copying and pasting it into xcode to have all the players preloaded in my app.
Basically, I hear core data is not a database (according to the Apple documentation) so im a little confused.
Using CoreData as a read-only pre-loaded data-store is very possible. In fact, CoreData's faulting mechanism may well work in your favour to keep runtime memory consumption low if the dataset is large. Using CoreData is almost certainly easier than fetching sub-sets of records as required from an SQLite database with SQL. CoreData also provides a solution for versioning, and model version updates.
To do this, you use an SQLite backing store and will need to write a tool to populate the initial model. Note that whilst it's just about feasible to use an SQLite database table editor to modify individual fields, you definitely can't create or delete rows using one.
In terms of a tool for populating the initial model, it makes a lot of sense to make this a MacOSX console or Cocoa application and run it as part of the application's build process. You include the SQLite database as a binary resource in your iOS application.
Building a graphical editing tool is actually far easier in MacOSX than iOS because of the extra KVO bindings on many controls provided by the cocoa framework - for instance, in NSTableView.
Alternatively, you can easily convert data from an existing format such as CSV or XML.
I almost always use Core Data, for pre-populated or empty databases. If you have to handle persisted data, you can either use .plist or database (mostly sqlite) files. The difference is that if you use .plist files, you load the data into NSDictionary objects. On the other hand, if you use Core Data, the persisted information is loaded into "managed" objects, wich are easier to work with. You have several advantages using Core Data (manage several contexts, data model editor, caching, etc.)
If you are not familiar with Core Data you should give it a try
Core Data may not truly be a database, but it holds a number of common features with SQLite databases.
Yes, Core Data is a good option. You would generally use an SQLite store to hold the data in your app. You can also write some code or a desktop app which will allow you to edit the preload database. You'd then copy the preload database to your Xcode project.
If you already have a solution using MESASqlite and everything works then there isn't a particular reason to change.
Basically, I hear core data is not a database (according to the Apple
documentation) so im a little confused.
Core Data is an object persistence framework: you put objects into a store, and you can get them back out later. So it's like a database, and it can use a database for the actual storage, but if you're thinking about it in terms of tables and rows instead of object graphs you should maybe consider just using SQLite yourself. Working with objects lets you build the smarts for manipulating your data into your classes, and the objects you pull out of a data store will have those behaviors.
is core data good if your app is to contain preloaded data.
Sure -- it's great for stuff like that. In fact, it's not uncommon to write a simple Mac program that takes data from somewhere else and adds it to a Core Data store using the same model you've created for your iOS app. You can build that data store into your iOS app along with the model, and it'll just work.

Data model persistence considerations in iOS

I've been working with sqlite database in my iOS app for data persistence, and I'm now trying to decide if it is worth to learn Core Data. I've been reading some documentation and posts regarding its pros and cons, but I find that deciding when to use Core Data or Sqlite is not so clear (for example, Core Data VS Sqlite or FMDB…?).
I need some guidance to know if I should learn and use Core Data, or using Sqlite is enough for me:
Already having sqlite scripts, is it possible to build a Core Data model from data in sqlite database? Afaik, (correct me if I'm wrong) you can use sqlite to persist Core Data objects, but is it possible to operate in reverse?
Is it appropiate Core Data for handling several users data? I need to take into account that different users could log in into the app in the same device.
Thanks in advance
Core Data is a wonderful framework but while it generally uses SQLite behind the scenes, you shouldn't think of Core Data as a database engine, but rather more of an object persistence framework. If you've got a lot of SQL code (especially bulk updates and the like), it might not be worth converting to Core Data. But Core Data has lots of wonderful performance optimizations, iCloud integration, etc., so it's worth examining in greater detail.
If you want background on Core Data, I'd suggest the Apple video Working with Core Data.
If you just want to simplify your SQLite code, check out FMDB.
In answer to your questions:
Already having sqlite scripts, is it possible to build a Core Data model from data in sqlite database? Afaik, (correct me if I'm wrong) you can use sqlite to persist Core Data objects, but is it possible to operate in reverse?
You generally have to redefine your Core Data model. It cannot just open your existing SQLite database (though once you define your model, you could write code to transfer the data from SQLite to Core Data).
Is it appropiate Core Data for handling several users data? I need to take into account that different users could log in into the app in the same device.
Yes, you could. You'd have to define your model to handle this manually, though (e.g. add a user identifier field and manually code predicates/filters results accordingly, much like you'd have to do in SQLite).
AppsDev,
Only you can judge whether to use Core Data or to stick with SQLite. As you've referenced my answer above, you know my view -- use Core Data. Let me put it in your context.
The big win is the family of abstractions that come with Core Data and how they map onto the Objective-C object model. This is something you have to handle manually from a SQLite application. (Can you do it? Yes. You will, though, most likely make a custom interface that is tuned to your SQL schema. It will have little reusability. This is a long term problem.)
As to the question of predicates versus SQL queries, this is a difference in world view. That said, as predicates can be applied to both NSSets and NSArrays, they have a utility beyond that required by Core Data. Knowing how to use predicates will be of value. For example, you could easily perform a query to get a collection of records and then use predicates to filter them, say for the search of a table view.
Everyone needs to pick when they are ready to embrace a specific pattern. SQL experts, unsurprisingly, like to stick with what they know. Dynamic language aficionados will choose differently. For iOS/OS X, embracing the dynamic language path will have ever increasing value to you as a developer.
Hence, my recommendation remains: use Core Data.
Andrew

Core Data requirement in a server side json app

I am trying to build an app for my website. I was under the impression that all I had to do was get and put json from the server to my phone. But then today I came across Core Data ( I am new to iOS).
So my question is, that to make a faster iOS app, is it a normal practice to fetch json data and save it as core data? Would apps like Facebook, Twitter follow this approach? or is just fetching and parsing json is a normal practice, and core data is not needed.
I am sorry if the question is dumb.
It is normal to retrieve data from a server (XML or JSON) and keep it in memory, if the memory foot print is reasonable. If you are talking about hundreds upon thousands of rows from a database, then persistent storage, with a dedicated data model(s) is probably the best choice; you can read it when needed.
If your needs are such that a complex data model is needed, one-to-many and/or many-to-many relationships, then consider Core Data (or SQLite directly).
You define your needs first, then try to define the data model that fits your needs (custom objects or maybe just a few instances of NSDictionary), then decide how that data needs to persist and how you plan on interacting with that data.
A few starting points:
Core Data Overview - Shoud help you decide if you should use it
RestKit - Just a suggestion
Tutorial on Data Persistence
Good luck.
I remember facing this anomaly not so long ago.
As already pointed out in some of the comments, it depends on your needs.
Not all data are eligible to be saved in core data after retrieving it from the web side. You might have integrity issues with that. To do the checks for large chunks of data might have even severe overheads. But if you feel that certain data are not likely to change very often then you can employ this technique for some portions.
If you decide to stick with Request/Fetch data, be sure you process the requests using NSOperation, GCD or NSThread, in order to avoid UI freezes.
Although, they are used for same purpose, they all have advantages and disadvantage, plz check out this topic on NSOperation vs Grand Central Dispatch
I hope this helps.

Should I be using Core Data?

I have developed an app that downloads the whole dataset into an array of objects. Should I be using core data to store the data? Aside from having some off-line data at hand for the user, are there any other advantages?
Thanks,
Steve
It's difficult to say with so little information. But if you need to store and access a bunch of data in iOS, Core Data is usually a good option.
It's obviously more complex than just storing the data in files (an array/dictionary can write its contents to disk) but you get a lot of other stuff for "free." Nice things include NSFetchResultController which means you can push your data into a table view with very little code. It makes things like undo and transactions easier.
Another option is using SQLite directly. If you know SQL and your data structure doesn't easily fit into an object graph (for whatever reason) or you want more control than Core Data can give you, it can be a good option.

Working with Core Data in iOS and saving states

I have read tutorials and found different methods for saving your data such as pure SQL, Core Data, Archives and NSUserDefaults.
I am thinking about creating an Application that will be kind of an RPG where I will create a class with different variables.
This class and it state must be saved an persist through App cancellation, iPhone booting and App updating.
I. Which ones of the previous methods fullfill this?
Also I have a Q about Core Data.
If I just want to store a variable, lets say a date for instance, in an entity. Lets say that the property is called dateJustNow and it is an attribute.
II. Do I have to create new rows for each saving of dateJustNow? Or are there other ways to save only ONE state of an variable and fetch it when needed?
Maybe I am mixing variables (singles) and attributes (collections)?
Sincerely yours
The rule is:
Use NSUserDefaults to save application state information. This is information about the operation of the app itself e.g. last launch time, preferred font, last open view etc. The user defaults are universally accessible and fast but lightweight. They can store only bits and pieces of data and they don't store any logic.
Use Core Data to model, manage and persist the actual data and logic that the app deals with. Core Data manages large, complex data and its associated logic.
In the case of game, you would use NSUserDefaults to save data about the operation of the app e.g. the user can set a preference for which view the app will startup to. However, the actual logic and data that encodes the rules of the game and changes in the game state should go into Core Data.
To me, it sounds like you are looking for an OR-mapper. Use SQLite directly to save states. If you were to write a multi-player online RPG, Core Data would have been great for the large amounts of data.
From this answer:
Although Core Data is a descendant of Apple's Enterprise Object
Framework, an object-relational mapper (ORM) that was/is tightly tied
to a relational backend, Core Data is not an ORM. It is, in fact, an
object graph management framework.
Also, here's a very good read: http://inessential.com/2010/02/26/on_switching_away_from_core_data

Resources