Saving model object into SQL DB - sql

I am reading several tutorials on how to use an SQL database with Cocoa, and it seems quite easy. I already took a look at a few wrappers too, but I can't find anywhere a way to save objects.
Is it correct to conform my model object to the NSCoding protocol, and just save the NSKeyedArchiver as an NSData object into the DB?
Should I do differently? Which is the best way?

You can use NSKeyedArchive too, but is not the best solution imho. Is like storing all data in a platform independent "database" an xml file. It wasn't created for that, it in't optimized for that.
I would create a NSSqlArchieve and map those fields which I want as how I want in native database, because: in different databases you can have custom fields, custom type fields , which myabe improve a select or other database operation. Or you just want to take advatage of some system table/data and can't find a mapping or is to slow or other problems.
NSData can be stored / retrieved to a Blob/Clob, since is binary data.
But all data convert to binary format and store it to database.... why to store there and why not into a file. Database was invented to store and make query from data.

Related

How to write data to file in Kotlin

A little while ago, I started learning Kotlin, and I have done its basics, variables, classes, lists, and arrays, etc. but the book I was learning from seemed to miss one important aspect, reading and writing to a file, maybe a function like "fwrite" in C++
So I searched google, and yes, reading and writing bytes were easy enough. However, I being used to C++'s open personality, wanted to make a "kind of" database.
In C++ I would simply make a struct and keep appending it to a file, and then read all the stored objects one by one, by placing "fread" in a for loop or just reading into an array of the struct in one go, as the struct was simply just the bytes allocated to the variables inside it.
However in Kotlin, there is no struct, instead, we use Data Class to group data. I was hoping there was an equally easy way to store data in a file in form of Data Class and read it into maybe a List of that class, or if that is not possible, maybe some other way to store grouped data that would be easy to read and write.
Easiest way is to use a serialization library. Kotlin already provides something for that
TL;DR;
Add KotlinX Serialization to your project, choose the serialization format you prefer (protobuf or cbor will fit, go for json if you prefer something more human readable although bigger in size), use the proper serializer for generating your ByteArray and write it to a file using Kotlin methods for that
Generating the ByteArray might be tricky, not sure as I'm telling this from memory. What I can tell for sure is that if you choose JSON you can get the string representation and write to a file. So I'm assuming the same will be valid for binary formats (but writing to a file in binary instead of strings)
What you need can be fulfilled by ROOM DATABASE
It is officially recommended by GOOGLE, It uses your Android application's internal Database which is made using SQLITE
You can read more info about ROOM at
https://developer.android.com/jetpack/androidx/releases/room?gclid=Cj0KCQjw5ZSWBhCVARIsALERCvwjmJqiRPAnSYjhOzhPXg8dJEYnqKVgcRxSmHRKoyCpnWAPQIWD4gAaAlBnEALw_wcB&gclsrc=aw.ds
It provided Data Object Class (DAO) and Entity Classes through which one can access the database TABLE using SQL Queries.
Also, it will check your queries at compile time for any errors in it.
Note: You need to have basic SQL Knowledge for building the queries for CRUD Operations

Saving Data - Core Data vs plist file

I'm writing an iOS applications that saves Music albums(just an exercise I'm doing for the fun of it) .
For every Album there's a singer, song names, time, and a picture
The final result will be a lot of objects with a lot of details including a picture attached to every object. Should I even consider doing something like that with plist? (can pictures be stored in a plist?)
What's the best way to save and access that data?
I'm new to iOS and from the training videos I've seen Core Data is not recommend for the beginner user. Is that really the case?
If I'm going with plist, should I create one plist for every genre for example rap.plist , rock.plist etc' or just a big data.plist?
Thanks
I would go for core data. If you choose the right template when you create your new project in xcode then reduce the once-off overhead work significantly.
With that simple structure I would say that the templates provides nearly everything you need. Just define your model and layout and off you go.
There is just the images where I would spend a bit more time in thinking it over. I personally never put the image data into core data itself. I rather stored them as file and within my core data model I just stored the path and filename to access it. As file name I simply used a timestamp. You could use some auto-increment or other unique id technique but a time stamp would do as well. It will not be visible to the user anyway.
I think the best way you can do this, since you are new to IOS is by using sqlite. Save all the information you want in your local database and display it on the screen.
You can use plist if you have data structure that is small.
Note that property lists should be used for data that consists primarily
of strings and numbers. They are very inefficient when used with large blocks
of binary data. A property list is probably the easiest to maintain, but it will be loaded into memory all at once. This could eat up a lot of the device's memory.
With Sqlite you will easily be able delete , edit, insert your data into the database.
Core data also uses sqlite for data storage only it helps you to manage your data objects, their relationships and dependencies with minimal code.
And since your are new getting started with core data would not be such a good idea i think.. so i would suggest start off with normal sqlite. Save the data in one of your folders of your app and store their path in the database.
You dont have to write different plists.. You can use the same one if you are using.
EDIT : here is a link that will help you with learning sqlite
http://www.iosdevelopment.be/sqlite-tutorial/
you need some more code to set up the core data stack (the store coordinator, the store, the object model, and a context)
it is a tad more complicated but that shouldnt scare you off.
Reading a plist is indeed dead easy but while good for smaller data (like the info.plist) it doesnt scale and soon you need a fullblown DB
As you edited your original question an decided to go with plist now.
In that case I would go for one plist per ablum and one overall plist for the list of albums.
You could, of course, use more plists for categories etc.
However, if you are thinking of data structures like categories you are far better off with core data. Especially when it comes to searching.
No one seems to be mentioning SQLLite, I would go that way and for reasons that I explain here ( https://stackoverflow.com/a/12619813/1104563 ). Hope this helps!
coredata is a apple provided persistant tool, while plist is XML file. The reason why core data is not recommended for beginner, I think, is core data is more difficult than plist from programming perspective. For your application, obviously core data is more suitable. But alternatively, you may also use archive file, that's between core data and plist.

Storing an array of 500 NSStrings in an iPhone app

I want to make an iPhone app that fetches up to 500 NSStrings from a server, and then it stores that data for later use.
I believe that my options are to use NSUserDefaults, store them in an SQLite database, or store them in an XML file.
Is that correct? Is an array of 500 NSStrings large? Which method should I use?
NSUserDefaults is meant for small amounts of application state and/or preferences.
SQLite is fine, but might be overkill if you're not using any RDBMS features. Internally, Core Data uses SQLite. If you're not interested in the object-graph, then Core Data is incredible overkill (and has a ton of overhead).
XML is meant for storing arbitrarily structured data. Is there any inherent structure to your data or it purely just a list of 500 strings? If there's no structure, then XML is overkill and you have to parse it, which means a non-trivial amount of code.
Two more options you didn't mention are: plist and NSKeyedArchiver. I'll leave it to you to read up on those.
Personally, I'd just go with a text file, but with the proviso that you haven't given enough information about the nature of the data or what you're going to do with it.
You can use
NSArray initWithContentsOfFile:
and
NSArray writeToFile:
to easily store your Strings in a file.

How should I store a bunch of data locally to display on a UITableView?

I have to display a lot of text preferably pre-formatted or formatted with NSString methods. Each row will have a detailed screen. In the detailed screen another UITableView will have sections for lets say "Definition", "Examples" etc each with only one row. In these rows I will be displaying the text, which spans multiple lines. Should I store all the text in a SQLite database like a column for each section? Are there other ways to store data locally?
You have quite a few different ways to store application data on your iPhone:
Using Flat Files
These are files that contain data in the format you decide it would be best to store it. They are useful for persisting small bits of text data that don't require a complicated structure and a strong relational organization in order to make sense.
Using Plist files
Property list files already have a key-value structure in place, that you can use to your advantage if your data lends itself well to this format. Native data types, such as NSDictionary and NSarray can be serialized and deserialized easily to and from this format.
Storing key-value data in NSUserDefaults
Typically used to store application settings and other small amount of data, NSUserDefaults are useful for holding simple data types without excessive complications.
Storing Information in an SQL Database
Useful for when your data is strongly structured and relational and you want to avoid rolling your own file-based data storage structure for time and performance reasons. The SQL language is a powerful tool for retrieving and persisting relational information and you can manage the complexity of your implementation by resorting to wrappers around SQLite, such as FMDB.
Using Core Data
If you plan on persisting and managing a complicated, dynamic object graph, without worrying on how to serialize and deserialize it from storage yourself, Core Data is your best bet. It can help you in many ways, from change tracking and undo support to relational structure maintenance and migration.
Here is a detailed Oreilly article explaining in more detail the particularities of most of these methods, a great read if you want to develop a solid understanding of the fundamentals.
Some methods are...
Core Data
Write to NSUserDefaults
Write to a file, like for example an NSDictionary to a plist
If all you're storing is a bunch of strings, it might make sense for you to keep it simple and just use NSUserDefaults or make a plist file and load it into an NSDictionary when you start your app. If you have actual objects with relationships and sub properties, then I'd look into core data.

should xml or sqlite3 be used?

I just started iOS development am currently developing an application that just reads data from a server and displays it onto the screen. What I am not sure of is whether to use XML or sqlite3 to store the data. Which method should be more preferred and why? thanks in advance.
It is important to remember they are two different things, suited to different tasks. Choose the one that fits the problem. (In this case I would likely use XML or "just plain text" because it sounds like just a simple download-cache. Either the raw response could be kept or, perhaps the data already transformed into objects and then automatically serialized into XML or whatnot. In any case, keep it simple.)
XML is (at the very core) a markup format. XML documents are a (hopefully well-defined) structure. There is a large set of tooling that supports manipulation and querying within a hierarchical "document" model. I use XML a good bit for a serialization format and also use it for local caching if appropriate (e.g. there are no non-hierarchical relationships). XML is often loaded entirely into memory (e.g. a DOM) for manipulation.
SQLite is a relational database that is designed around tables and relationships between sets of tables. Being able to run (complex) queries is where a relational database really shines. SQLite is also very fast and can process large data-sets which can't all fit in memory. Columns in SQLite can also contain text (read: XML) so the approaches are not orthogonal.
Happy coding.
Probably all depends on how data is processed after it was stored. If data must be sorted, uses specific selection etc. then, sqlite is better solution.
Second, not so important, concern is how much data will be stored, if it's just one "table" with 10 rows then sqlite is probably too much for it.
If you want to read data from server and want to display on screen and don't need to save it locally then use XML.
If you want to store it locally and don't want to fetch from server then use XML files or sqlite database in your project.
If you want to fetch from server and also to store it locally then first use XML to fetch data and then use sqlite to store it locally.
and look at #pst answer for what is the difference between them.