ios swift 4 local database explanation - ios

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.

Related

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.

Use Core Data or not?

I am creating an app that will show users what the statuses of some devices are. The status can change at any time and the users will be able to refresh the data. I want to use a way of storing the data so users are always able to see the latest state without needing an internet connection and to reduce the loading time.
I am currently deciding between Core data and SQLite.
For my situation, which one should I choose and why?
First of all Core data is not a database. So if you have feeling of database usage in future than move to SQLite.
Core data is a framework that manages object graph. Core data persist that object graph by writing it to disk.
Where as SQLite is a lighter version of SQL, So it limits some complex functionality of SQL language, And yes it is a pure database.
Core data is not a database how ever you can manage object and entities as like database tables and attributes as a columns.
Conclusion:
Go for Core data, it will reduce the time of database connection opening and querying. As I said it is not a database so all database limitations are not in a picture.
Core Data is the best option to use but if somehow you want to port the application to android or windows and want to keep the code similar then you can go for SQLITE as SQLite is supported by all major platforms. Whereas core data is only part of iOS
Using CoreData is always a better option.
Core Data is built on top of SQLite, so you work on SQLite either way :)
Core Data works with Objects so no worries working with Queries.
Complex queries and data retrieval is easier.
Database locks and other sync errors are auto handled.
Finally, it has everything that you require at the moment.

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

Is it possible to use sqlite queries done through code to access the core data database?

Just curious if we can access the core data database through sqlite queries. On the process of searching, I've found Chris Miles' post for debugging core data with sqlite. Here, he points out that we can use the terminal to input sqlite queries and then actually access the core data database.
Kindly clarify if this is possible through objective - c code. If this can be done, may I ask some links for good tutorials I can study on. Thanks!
You can certainly make C sqlite3 calls from inside Objective-C methods. However, if you've gone to the trouble of defining your data model in Core Data and creating a managed object environment, it's hard to imagine why you would want to circumvent that.
Consider also that there's no guarantee that the current table layout under Core Data will stay the same with the next iOS release, so anything your assume about the storage is fragile.

Resources