tutorial on creating an ios sqlite database application | ios | iphone

8
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone This link will also be an IBOutlet and the name is going to be : wineViewer. Setup your current Git, or even not, source control and finished the advance of the project. A Person will possibly be prompted in order to save the actual file to the file system, (naturally). Anyone may add information by selecting the table and also selecting the browse along with data tab. A Person could give any kind of meaningful title you want. Scroll down until you discover the sqlite_3.0.lib. The following operation will try to open your database, sqlite3_open prior to environment up the Select statement and also sql3_stmt: if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) ... Create IOS 5 Project sqlite3_stmt *sqlStatement; @synthesize wineViewer; ... [self setWinename:nil]; NSMutableArray *wineArray = [[NSMutableArray alloc] init]; ... NSLog(@"Cannot find database file '%@'.", dbPath); if(!success) else NSFileManager *fileMgr = [NSFileManager defaultManager]; - (IBAction)GetWineListing:(id)sender Well CRUD is a bit of the stretch. With Regard To this part, 4 labels (UILabel) tend to be required: one regarding Wine Title and the worth from your database as well as likewise for the a pair of others: 1 regarding Wine Ranking and the corresponding worth from your database that will be stored inside the NSMutableArray. Click your next Bottle for you to have the next listing. [wineArray addObject:MyWine]; const char *sql = "SELECT id, Wine, Rating, Photo FROM WineTbl"; if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)

Upload: chunkyquery3536

Post on 21-Jul-2016

9 views

Category:

Documents


0 download

DESCRIPTION

This link will also be an IBOutlet and the name is going to be : wineViewer. Setup your current Git,

TRANSCRIPT

Page 1: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

Tutorial on Creating an iOS SQLite Database Application |iOS | iPhone

This link will also be an IBOutlet and the name is going to be : wineViewer. Setup your current Git,or even not, source control and finished the advance of the project. A Person will possibly beprompted in order to save the actual file to the file system, (naturally). Anyone may add informationby selecting the table and also selecting the browse along with data tab. A Person could give anykind of meaningful title you want. Scroll down until you discover the sqlite_3.0.lib. The followingoperation will try to open your database, sqlite3_open prior to environment up the Select statementand also sql3_stmt:

if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)

...

Create IOS 5 Project

sqlite3_stmt *sqlStatement;

@synthesize wineViewer;

...

[self setWinename:nil];

NSMutableArray *wineArray = [[NSMutableArray alloc] init];

...

NSLog(@"Cannot find database file '%@'.", dbPath);

if(!success)

else

NSFileManager *fileMgr = [NSFileManager defaultManager];

- (IBAction)GetWineListing:(id)sender

Well CRUD is a bit of the stretch. With Regard To this part, 4 labels (UILabel) tend to be required:one regarding Wine Title and the worth from your database as well as likewise for the a pair ofothers: 1 regarding Wine Ranking and the corresponding worth from your database that will bestored inside the NSMutableArray. Click your next Bottle for you to have the next listing.

[wineArray addObject:MyWine];

const char *sql = "SELECT id, Wine, Rating, Photo FROM WineTbl";

if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)

Page 2: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

// MyWineList

...

BOOL achievement = [fileMgr fileExistsAtPath:dbPath];

WineList *MyWine = [[WineList alloc]init];

sqlite3_stmt *sqlStatement;

Test Your Own App

...

[super viewDidUnload];

if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))

Launch XCode 4.2 and also produce a Single-View IOS 5 application. When FireFox will be installed,install the SQLite Manager from your Add-on Manager.

//

NSLog(@"An exception occured: %@", [exception reason]);

const char *sql = "SELECT id, Wine, Rating, Photo FROM WineTbl";

iOS and SQLite make a effective mixture pertaining to creating data persistent iPad, iPhone or iPodTouch mobile applications. For You To upload a image, click on the paper clip icon next to the blobfield. In your event that you don't possess them, these people can be downloaded and also installedfrom your FireFox web site. Thus your own WineList should contain four @synthesize statements, 14 each along with every property (Figure 11).

...

return wineArray;

@try

MyWine.wineId = sqlite3_column_int(sqlStatement, 0);

NSMutableArray *wineArray = [[NSMutableArray alloc] init];

if (++currentIndex == [self.wines count])

For your sake regarding this tutorial, I will pre-populate your database with some wine entries alongwith images in the web. Regarding this tutorial it can be really just a R (read) operation. Setup theactual getter as well as setters:

Here may end up being the complete source code of the various files which were created.

Page 3: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

MyWineLists * mywines =[[MyWineLists alloc] init];

NSString *dbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"IOSDB.sqlite"];

The SQLite Manager can be launched from the Firefox menu or perhaps Resources menu dependingaround the edition you are using (see figure 1).

MyWineLists.m

- (void)viewDidLoad

// Copyright (c) 2011 kCodebook. (Figure 4 and also figure 5).

NSLog(@"An error features occured.");

self.wines = [mywines getMyWines];

NSLog(@"Problem with prepare statement");

#import "MyWineLists.h"

...

To finish off the actual app, several code needs to become added to the ViewController header aswell as implementation files. This kind of is likely to be an IBAction and the title of the method:GetWineListing. take note where you're saving it because you tend to be heading to copy the filelater on in your project.

@synthesize wine;

[self.wineViewer setImage:aWine.photo];

Next declare a NSFileManager object, a new NSString object along with a Bool object:

in the particular viewDidUnload set your own properties for you to nil in order to release them frommemory

This just about protects the particular in the cRud operations. Open Up it along with open the libfolder. the iOS SDK provides native assistance regarding SQLite by means of the particularutilisation of the C programming language. An Individual will need to add the actuallibsqlite_3.0.dylib file for you to your project (figure 6), thus progress up a pair of or three levels (seeGo to Enclosing folder within the Finder menu) until you obtain for the usr folder. all rightsreserved.

//

while (sqlite3_step(sqlStatement)==SQLITE_ROW)

NSLog(@"Cannot find database file '%@'.", dbPath);

Page 4: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

...

@synthesize photo;

[wineArray addObject:MyWine];

NSLog(@"Problem together with prepare statement");

int rawLen = sqlite3_column_bytes(sqlStatement, 3);

[self setWinerating:nil];

Expand the actual Frameworks folder, correct click upon among your frameworks along with selectDisplay within Finder to spread out Finder in the Framework location. Right After the actual app willbe finished initializing an individual must have coming from data along with image about screen. Ifthe actual file will be located, achievement is likely to be true. start through selecting the really firstlabel as well as dragging any connection line (Ctrl+left mouse button) to the header file involvingthe final curly brace and also the @end directive. in this file, the particular gut in the big event theoperations will just take place.

@synthesize winename;

NSLog(@"An error has occured.");

Source Code

...

Now you'll end up being able to near the particular database from your Firefox menu along withFirefox also since we won't need any longer for the tutorial.

Start through locating and opening the actual storyboard file. (figure 6).

[self.winename setText:aWine.wine];

return wineArray;

To begin produce the NSMutableArray method getMyWines and add an array pointer variable:

Create the actual database

MyWine.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];

MyWine.wineId = sqlite3_column_int(sqlStatement, 0);

Create UI Operations

Create CRUD Operations

MyWine.wine = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];

Page 5: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

- (NSMutableArray *) getMyWines

@finally

...

Next, click around the new table button (figure 3) to create a brand new table, once again I willleave up for you for you to identify it some thing useful. As your final step for your UI, drag a newUIToolbar as well as put it with the underside in the screen and also rename the particular includedbutton: Subsequent Bottle (Figure 14).

//

(c) klanguedoc, 2011

// created by Kevin Languedoc on 11/25/11.

[super viewDidLoad];

To start with, a person will end up being needing FireFox coming from Mozilla and furthermore theSQLite Database Manager plugin. Inside the particular Popup, select IBOutlet and also get into aname like: winename. Furthermore add any NSMutableArray object:

// MyWineLists.m

Create a new Team (File | New Group) or even from your (Context Menu | New Group). Lastly dragany link line from the button in the Toolbar. Repeat the method for your subsequent pair of files:MyWineList, (or anyone can select an identity such as WinesDAO).

WineList *MyWine = [[WineList alloc]init];

If the database will be successfully opened, the particular sqlite3_prepare will attempt to executethe particular sqlStatement. for your image, repeat the same operation as the 2 preceding ones.Carry On with second label which will contain the actual ranking information. for this tutorial, mynamed the table wineTbl and I have created four columns: id [primary, autoinc, integer], winename[varchar], winerating [varchar] and also wineimage [blob].

...

MyWine.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];

WineList *aWine = (WineList *) [self.wines objectAtIndex: currentIndex];

const char *raw = sqlite3_column_blob(sqlStatement, 3);

@synthesize rating;

@catch (NSException *exception)

For your WineList class generate 4 properties inside the WineList.h (header) file, one regardingevery column in the wineTbl (Figure 10):

Page 6: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

You should have small filled inside dot in the margin indicating that connections are already made.

- (void)viewDidUnload

...

MyWine.wine = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];

...

@implementation MyWineLists

if(!success)

Configure SQLite

#import "WineList.h"

The dbPath will include for the filename as well as path of the SQLite database that is going to bepassed to the fileMgr. This will be also an IBOutlet and the name will be: winerating. An Individualshould have a single blank scene (View Controller). for the actual images, drag an UIImageView tothe scene. Select the actual Objective-C node then the particular Objective-C class template.

if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))

...

MyWine.photo = [[UIImage alloc] initWithData:data];

currentIndex=0;

Ok, we get been done. Subsequent test to determine when the file had been located of course, if notnecessarily log an error. Click about the run button to launch the app. Regarding the actualMyWineLists header file, any sqlite3 object is actually declared and an NSMutableArray method(figure 11):

Next select the actual project root, correct click as well as select Display in Finder. Your next thingwill involve environment up your UI, creating IBActions as well as IBOutlets connections. Thisparticular tutorial will walk an individual by means of how to setup a SQLite database applicationalso to read text along with images from your database in to be able to a scene.

[self.wineViewer setImage:((WineList *) [self.wines objectAtIndex:0]).photo];

BOOL good results = [fileMgr fileExistsAtPath:dbPath];

. (See figure 12, 13).

Setup DAO Operations

[self.winerating setText:aWine.rating];

Page 7: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

Next open your implementation file. Drag your file for your Frameworks being careful for you toNOT copy file to the frameworks, nevertheless ONLY create a reference (Figure 7).

@synthesize winerating;

@finally

@try

To implement these objects, open up the actual MyWineLists.m file. Give it the meaningful title aswell as select Storyboard and also ARC. Find the sql database an individual produced within the 1sta component of this tutorial along with copy it in for you to the project team in locations you projectheader and also implementations files are (Figure 8).

@synthesize wines;

[self setWineViewer:nil];

[self.winename setText:((WineList *) [self.wines objectAtIndex:0]).wine];

NSLog(@"An exception occured: %@", [exception reason]);

NSData *data = [NSData dataWithBytes:raw length:rawLen];

while (sqlite3_step(sqlStatement)==SQLITE_ROW)

@end

http://hubpages.com/hub/Tutorial-on-Creating-an-IOS-5-SQLite-Database-Application-IOS-5-SQLite

NSData *data = [NSData dataWithBytes:raw length:rawLen];

In the particular viewDidLoad, that is known as when the app can be finished initializing itself, addpointers to hold the particular initial information in the array so the app will display someinformation and image which is positioned at index 0.

[self.winerating setText:((WineList *) [self.wines objectAtIndex:0]).rating];

NSFileManager *fileMgr = [NSFileManager defaultManager];

const char *raw = sqlite3_column_blob(sqlStatement, 3);

static NSInteger currentIndex = 0;

Click around the new Database button (figure 2) to produce a brand name new database.Consequently to setup the particular IBAction as well as IBOutlet, open the header file alongsideyour storyboard simply by clicking about the Assistant Editor, the face icon inside the Toolbar(Figure 14). Ok now the application is actually likely to want DAO courses for the CRUD (Read)operations, consequently in the big event you haven't already done so, create a brand name newObjective-C class: MyWineLists or perhaps whatever you need so really long as the declaration andimplementation works. Select the Model group along with from your File menu or even Context

Page 8: Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone

menu | select New File. next generate a couple of Objective-C implementation files as well ascorresponding header files. name it "Model". If the particular statement is actually effectivelyexecuted resulting in the outcome set getting returned, then execute a small while loop to traversethe end result set assigning your values towards the NSMutableArray fields.

MyWine.photo = [[UIImage alloc] initWithData:data];

NSString *dbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"IOSDB.sqlite"];

Give the file a new name: WineList (if you may be next this tutorial), select NSObject because theSubclass and create the particular file. Note, the actual SQLite extension will be routinely appended.Once Again select the NSObject as the Subclass and create your file (Figure 9).

@catch (NSException *exception)

@synthesize wineId;

//

Finally implement the actual GetWineListing method, so once the user clicks about the button, yourindex gets incremented and also retrieves your data in the selected index number.

int rawLen = sqlite3_column_bytes(sqlStatement, 3);

Next open up the actual WineList.m (implementation) file to set up the getter and setter methods