Data Persistence Sisoft Technologies Pvt Ltd

Slides:



Advertisements
Similar presentations
Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
Advertisements

CC SQL Utilities.
Persistence 2: SQLite CS 344 Mobile App Development Robert Muller.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
--What is a Database--1 What is a database What is a Database.
Using Objects and Properties
C++ fundamentals.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
Codeigniter is an open source web application. It occupies a very small amount of space in the memory and is most useful for developers who aim to develop.
Data File Access API : Under the Hood Simon Horwith CTO Etrilogy Ltd.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Andrew S. Budarevsky Adaptive Application Data Management Overview.
1 CS 430 Database Theory Winter 2005 Lecture 2: General Concepts.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Persistence CS 344 Mobile App Development Robert Muller.
Chapter 18 Object Database Management Systems. Outline Motivation for object database management Object-oriented principles Architectures for object database.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
CHAPTER 9 File Storage Shared Preferences SQLite.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
Data in Windows 10 UWP Andy Wigley XML, JSON, SQLite or EF Core ?
Introduction to Database Programming with Python Gary Stewart
Data Persistence Chapter 9. Objectives Learn about data storage methods Understand use of Shared Preferences Understand file-based storage and the differences.
Introduction to Mongo DB(NO SQL data Base)
Location And Maps Sisoft Technologies Pvt Ltd
Databases and DBMSs Todd S. Bacastow January 2005.
Fundamentals of DBMS Notes-1.
Web Services Sisoft Technologies Pvt Ltd
Drawing And Animations
IOS Design Patterns Sisoft Technologies Pvt Ltd
Mobile Applications (Android Programming)
SQL – Python and Databases
Table spaces.
Working in the Forms Developer Environment
Notification Sisoft Technologies Pvt Ltd
CIS 136 Building Mobile Apps
MongoDB Er. Shiva K. Shrestha ME Computer, NCIT
Media Library Sisoft Technologies Pvt Ltd
Java Beans Sagun Dhakhwa.
In-situ Visualization using VisIt
Database application MySQL Database and PhpMyAdmin
Mobile Application Development Chapter 5 [Persistent Data in Android]
Activities and Intents
Chapter 11: File System Implementation
Review: Two Programming Paradigms
Introduction What is a Database?.
Entity Framework By: Casey Griffin.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Intro To Design 1 Elementary School Library: User Sub-System Class Diagrams Software Engineering CSCI-3321 Dr. Tom Hicks Computer Science Department.
DATABASE MANAGEMENT SYSTEM
Chapter 11: File System Implementation
Introduction to Database Systems
EEC-492/693/793 iPhone Application Development
Data, Databases, and DBMSs
Chapter 11: File System Implementation
Introduction to .NetTiers
CIS 136 Building Mobile Apps
CIS16 Application Programming with Visual Basic
Chapter 2: Operating-System Structures
Computer Science Projects Database Theory / Prototypes
A QUICK START TO OPL IBM ILOG OPL V6.3 > Starting Kit >
Chapter 11: File System Implementation
Chapter 2: Operating-System Structures
Preference Activity class
Presentation transcript:

Data Persistence Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283

App SandBox Directory The operating system installs each iOS application in a sandbox directory, which contains the application bundle directory and three additional directories, Documents, Library, and tmp The Documents directory is meant for user data The Library directory is used for application data that isn't strictly tied to the user The tmp directory should only be used for temporarily storing files and this is not included in backups The application's sandbox directory, often referred to as its home directory, can be accessed by calling a simple Foundation function, NSHomeDirectory() NSLog(@"HOME > %@", NSHomeDirectory());

Data Persistence Options User defaults Property lists SQLite Core Data

NSUserDefaults The NSUserDefaults class provides a programmatic interface for interacting with the defaults system The defaults system allows an application to customize its behaviour to match a user’s preferences NSUserDefault *nud=[NSUserDefaults standardUserDefaults] [nud setObject:@”xxxx” forKey:@”YYYY”] NSString *user=[nud objectForKey:@”YYYY] ;

USING plist A property list is a representation of a hierarchy of objects that can be stored in the file system and reconstituted later Property lists give applications a lightweight and portable way to store small amounts of data Property lists are easy to create programmatically and are even easier to serialize into a representation that is persistent

Property List Types and Objects Property lists consist only of certain types of data: dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values

Adding plist

Plist view

Reading pList Find out the path of plist file NSString *path = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"]; Property List may be an Dictionary or an Array. Load the file content and read the data into arrays Array NSMutableArray *data=[[NSMutableArray alloc] initWithContentsOfFile:path] ; Dictionary NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; NSArray *tableData = [dict allValues];

Writing pList NSString* plistPath = nil; NSFileManager* manager = [NSFileManager defaultManager]; if (plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents/Info.plist"]) { if ([manager isWritableFileAtPath:plistPath]) { NSMutableDictionary* infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; [infoDict setObject:[NSNumber numberWithBool:hidden] forKey:@"LSUIElement"]; [infoDict writeToFile:plistPath atomically:NO]; [manager changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] atPath: [[NSBundle mainBundle] bundlePath]]; } }

SQLite

Sqlite iOS includes the popular SQLite library, a lightweight yet powerful relational database engine that is easily embedded into an application Used in countless applications across many platforms, SQLite is considered a de facto industry standard for lightweight embedded SQL database programming Unlike the object-oriented Core Data framework, SQLite uses a procedural, SQL-focused API to manipulate the data tables directly

SQLite Datatypes SQLite is weakly typed having following storage types: NULL: indicates a NULL value INTEGER: used to store an integer, according to the size can be used to store 1,2,3,4,6,8. REAL: floating-point TEXT: In accordance with string to store BLOB: according to the binary value is stored without any change.

Sqlite API Commands sqlite3_open() : This routine opens a connection to an SQLite database file and returns a database connection object. int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ );

Sqlite API Commands sqlite3_exec() : convenience wrapper around sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize(), that allows an application to run multiple statements of SQL without having to use a lot of C code int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ );

The most important SQLite API commands

Developing Apps using Sqlite Configure the project to include the SQLite dynamic library (libsqlite3.dylib) in choose frameworks. Import the sqlite3.h header file into any files where we make use of SQLite Declare a variable pointer to a structure of type sqlite3 that will act as the reference to our database @property (nonatomic) sqlite3 *contactDB; Declare an NSString property in which to store the path to the database @property (strong, nonatomic) NSString *databasePath;

Sqlite: Creating Databases Database will reside in application sandbox. App sandbox home path can be find by method NSHomeDirectory() Build the path to the database file databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"student.db"]]; When the application is launched it will need to check whether the database file already exists NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath: databasePath ] == NO) if file does not exist, create both the database file and table(s) within the database if (sqlite3_open(dbpath, &database) == SQLITE_OK)

Sqlite Database Drawbacks One of the most important drawback of sqlite database is that it does not provide database migration Its is slower than core data No interface provided ios sdk you can use sqlite toolkit in mozila firefox For scratch start on sqlite click Here http://www.tutorialspoint.com/ios/ios_sqlite_database.htm

Core Data https://www.techotopia.com/index.php/An_iOS_7_Core_Data_Tutorial

Core Data Core data is another but important way for data persistance Core Data Features: Schema migration Relationship maintenance Change tracking and undo support Automatic validation of property values Grouping, filtering, and organizing data in memory and in the user interface Automatic support for storing objects in external data repositories Sophisticated query compilation(NSPredicate) Full, automatic, support for key-value coding and key-value observing

Why Core Data Code Reduction: 50% to 70% code is reduced for model class you write with core data Greater Performance: mature code base whose quality is maintained through unit tests Tool Integration: In addition to the benefits of the framework itself, Core Data integrates well with the OS X tool chain. The model design tools allow you to create your schema graphically, quickly and easily

The Core Data Stack

managed object context The managed object context is an instance of NSManagedObjectContext A context represents a single object space, or scratch pad, in an application Its primary responsibility is to manage a collection of managed objects Data insert,fetch done on context object The context is a powerful object that your application will be interacting with the most

Managed Objects A managed object is an instance of NSManagedObject or of a subclass of NSManagedObject Conceptually, it’s an object representation of a record in a table in a database, so it’s a model(as in mvc) object that is managed by Core Data Managed objects represent the data you operate on in your application

The Managed Object Model A managed object model is an instance of NSManagedObjectModel It’s an object representation of a schema that describes your database, and so the managed objects you use in your application A model is a collection of entity description objects (instances of NSEntityDescription) An entity description describes an entity (a table in a database) in terms of its name, the name of the class used to represent the entity in your application, and what properties (attributes and relationships) it has

Persistent Store Coordinator The persistent store coordinator plays a central role in how Core Data manages data However, you don’t often interact with the coordinator directly when you use the framework It manages a collection of persistent object stores A persistent object store represents an external store (file) of persisted data It’s the object that actually maps between objects in your application and records in the database

Adding Core Data Project

Defining Model: Core Data Model Editor Select your projectName.xcodedatamodel file and add entity(Table)

Adding Attributes And Relationships

Defining Attribute

Definning Relationship

Core Data: Classes NSManagedObjectContext NSManagedObject NSEntityDescription NSFetchRequest NSPredicate

Get NSManagedObjectContext - (NSManagedObjectContext *)managedObjectContext { NSManagedObjectContext *context = nil; id delegate = [[UIApplication sharedApplication] delegate]; if ([delegate performSelector:@selector(managedObjectContext)]) { context = [delegate managedObjectContext]; } return context;

Insert and Save - NSManagedObject *newBooks; newBooks = [NSEntityDescription insertNewObjectForEntityForName:@"Books” inManagedObjectContext:context]; [newBooks setValue:_book_name.text forKey:@"bookname"]; [newBooks setValue:_author_name.text forKey:@"authorname"] ; NSError *error; BOOL ret= [context save:&error] ; if (ret== NO){ NSLog(@"Error:%@", [error localizedFailureReason]); } else { NSLog(@"Record Saved\n");

Fetch or Query NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts” inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(bookName = %@)", _book_name.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if ([objects count] == 0) { NSLog(@"No Matches") ;} else { matches = objects[0]; _book_name.text = [matches valueForKey:@"bookName"]; _author_name.text = [matches valueForKey:@"authorName"]; NSLog(@"%lu matches found", (unsigned long)[objects count]);}

What Core Data Is Not Core Data is not a relational database or a relational database management system (RDBMS) Core Data does not remove the need to write code Core Data does not rely on Cocoa bindings, You can readily create a Core Data application without a user interface For more on Core Data click Here