Data model persistence considerations in iOS - 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

Related

ios swift 4 local database explanation

I am migrating with a project from Android to iOs. I am totally new to xCode and got already only some practice with Swift (o.w. I am just new with programming for iOs)
So I need help or simple explanation about local databases on iOs.
I've read about CoreData and about SQLite for iOs. I know that CoreData is "not just a database!" and I can't ask question about CoreData vs SQLite".. But I have to.. I try to understand but it's not written so clearly and simply as I need. If SQLite isn't naturally supported by xcode and iOs is it still safe to use it? Is it good to use CoreData when u need it only for local database?
So, what should I use when I need to store data on my phone and my database records on a local device won't be even more than 50000? The data will come from Server (JSON) and some of it from the device measurements
You can use both SQLite and Core Data. They are both widely used and you will not have any issues using them. If you want to use SQLite I would suggest using FMDB because it will make using the SQLite database easier. Core Data is very performant but you say you will not have a ton of data so it could be overkill and it is a bit verbose to use.
I think SQLite has an advantage if you want your server to be able to send you a straight up SQLite file as a download. SQLite is supported everywhere so it is easy to contruct a database on the server and send it over to the your phone as a file. Core Data is only supported on iOS so you will have to translate the information from your JSON, but you stated that you will already be doing that.
Personally, I think Realm is the easiest local database to get set up for iOS. I was able to add it to some of our code bases surprisingly fast and they have good documentation. They have a pretty big community and it is easy to get help as well as a wealth of tutorials on how to get started. Realm is also cross platform so you could use the same database in your Android app. If you are familiar with database ORM's for Code First database approaches then you will feel at home with Realm.
At the company I work at we use all three in our production apps, so it is merely a question of taste and other requirements outside of you control. All three will do what you want to do.
From the Apple Reference
What is Core Data?
Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.
From this you can see the essential difference between Core Data and a database, such as sqlite; Core Data deals with objects. Persistence of those objects, while a common use of Core Data, is not compulsory. The Core Data framework can make use of different backing stores and sqlite is one of the most common stores.
When you deal with a database you have to think about tables and rows and you have to handle the conversion between the row data and your in-memory object. With Core Data, your model objects can subclass NSManagedObject and you can persist and restore them directly with Core Data.
With a database you can use foreign keys to relate rows between tables and you typically use a join or another query to obtain the related data. With Core Data you can simply assign the reference to the related object to a property of the first object e.g. employee.manager = someOtherEmployee and Core Data will manage the relationship for you when you persist the data. When you retrieve the data you can refer to employee.manager to get a reference to the manager object without needing to explicitly perform a query/fetch; Core Data will retrieve the object from the backing store automatically if necessary.
Unless you need complex queries or joins, you probably don't need sqlite. There is a bit of a learning curve with Core Data, but the first hurdle is understanding that it isn't a database and you shouldn't treat it like one.
The advantage of using something like sqlite can be portability; a database and queries that you are using in an Android app or website can be used in an iOS app.
To give you an idea of how Core Data could work in your situation;
Your data is coming as JSON objects, so using Swift 4 Codeable you can easily convert that JSON into a collection of Swift objects.
Xcode will create the Core Data Entity objects for you based on your Core Data model.
All you need to do is add extensions to these classes to implement Codeable and then you can persist your JSON data locally with virtually no additional code.

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.

Multiples tables and relationships

What the best way and how to work with multiples tables in iOS project and does FMDB supports relationships between tables?
Should I use Coredata or the FMDB wrapper?
Whatever you want to do, you can use either Core Data or FMDB + SQLite.
Basically, if one of the follow is true, I suggest using SQLite.
Performance is really important
You already have a huge SQLite database from elsewhere
You plan on making the database cross-platform somehow
Have a look at this blog post to read about the difference between SQLite and Core Data.
However, in most cases Core Data is a better way to go. Core Data is a great framework that helps you keep your consistency (using object graphs) and is really quite easy to use. It has received a bad rep for its performance, but it is actually not that bad. For instance, over-fetching is a common thing that is used to improve performance. This means fetching lots of data and then filtering out the data you actually want. This works great in iOS devices since their RAM is actually really good these days. Use it!
Also, if you plan on using Core Data, you should understand that it is NOT a wrapper for SQLite. You should not be thinking about tables like you normally would. In Core Data you have an object graph with entities instead of tables.
Conclusion:
Use Core Data unless you already have a SQLite database form elsewhere OR performance matters a lot (and I mean a lot).
There is no one good question for this. It's depends on project.
In my opinion if you have already some data which you want to import to the application, and you will facing huge amount of data in your database, you should go for pure sqlite (and maybe FMDB).
If you are connecting to REST, want to use TableViews, starting from empty database CoreData will right answer for you.
FMDB is only a wrapper on sqlite so it will have relations, because sqlite has.

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.

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.

Resources