Should I be using Core Data? - ios

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.

Related

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

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.

Usage of Core Data other than a Database

i am new to this Core data. When i search for tutorials, I'm seeing this sentence Core Data is not a database everywhere on the internet.
If it is not a database, why are we using it as a database?
For what purpose Core Data is initially created?
Is there any other way Core Data was used before/will be used in
future (Other than as a DB)?
Sorry for my English.
Thanks for the time.. (:
Actually Core Data is a bridge between the code and the underlying database (like SQLite or XML...). Core Data is not a database, but uses SQLite (or XML...) for persistence. The main purpose of Core Data is to manage memory objects and object graphs easily without having to do it manually through a SQLite library for instance. It is possible to use Core Data without persistence is you want (using In-Memory stores).
Here is the documentation : https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075-CH2-SW1
Bye!
If it is not a database, why are we using it as a database?
"We" are not necessarily doing so, depending on who you mean by "we". Core Data can be used in a database-like manner, keeping in mind the Core Data vs. SQL differences others have noted. But that's not the only possible use.
Statements that Core Data isn't a database are mostly intended to prevent people from thinking of Core Data in the same sense as SQL. That sort of thinking leads to badly designed data models, since the approach is different. It can be used as a database in the generic sense of the storing structured data but it's important to not assume that it works like other databases you may have used.
For what purpose Core Data is initially created?
Is there any other way Core Data was used before/will be used in future (Other than as a DB)?
Core Data was created to fill what might have been perceived as a missing piece in Apple's frameworks. They generally take the MVC approach. There were classes to help in designing and implementing views (in these pre-iOS days that meant AppKit) and with controller classes (for example NSArrayController, also an OS X class). But model support was limited to NSCoding, which required a lot of repetitive code. Custom solutions also had trouble scaling to large amounts of data-- for example NSCoding doesn't help you load only part of a large document graph, because it recursively works its way through the entire object hierarchy.
Core Data was added with the purpose of making it easier to design and implement the model layer of an app. It's no accident that the document you edit to design the data is called a data model and not a schema.
The idea was (and is) that you could
Design your data model visually in Xcode
Create and use instances of your model objects
Read and save those objects in a file
...all without ever needing to write your own code to figure out how to convert your model objects to and from something that could be written into a file, or with the mechanics of opening a file, reading/writing it, and saving it. You'd just create objects as needed and then call save on NSManagedObjectContext. The small bit of code that was concerned with locating and opening the file was all pretty much the same in any app, so while it was still required it was mostly no longer the app developer's concern (and in iOS 10, NSPersistentContainer eliminates even this). You'd also get the benefit of only needing to load the parts of your object graph that you currently needed instead of loading everything every time.
As you've noticed, in practice Core Data is commonly used more or less like a database, and it works for that. But it's not designed to be limited to such uses.
Yes it is true , Core data is not a Database, though internally it saves data using sqlite. We use Coredata for persistent data which means we should be able to save the data and use it even after closing and reopening the app. There are various ways to store data like Sqlite,Plist,UserDefaults and CoreData. Coredata does not maintain any relations like SQlite. It means there are no keys like primary and foreign etc. Coredata allows you to deal with data in Object Oriented Approach. You can easily work with data operations even you don't have knowledge about DB queries.

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.

Resources