archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • IPhone Database Implementation using SQLite - Techotopia
    a database file named contacts db in its documents directory the file will be located on the host system in the following folder Users user Library Application Support iPhone Simulator User Applications id Documents Where user is the login name of the user running the iPhone Simulator session and id is the unique ID of the application Preparing an iPhone Application Project for SQLite Integration By default the Xcode environment does not assume that you will be including SQLite in your application When developing SQLite based applications a few additional steps are required to ensure the code will compile when the application is built Firstly the project needs to be configured to include the libsqlite3 dylib dynamic library during the link phase of the build process To achieve this hold down the Ctrl key and click with the mouse on the Frameworks entry of the Groups and Files panel located on the left hand side of the Xcode project window From the resulting menu select the Add Existing Frameworks option From the list of framework options scroll down to the libsqlite3 dylib entry select it and click on the Add button Secondly the sqlite3 h include file must be imported into any files where references are made to SQLite definitions declaration or functions This file in located in the usr include directory and may be imported when needed as follows import usr include sqlite3 h Key SQLite Functions When implementing a database using SQLite it will be necessary to utilize a number of C functions contained within the libsqlite3 dylib library A summary of the most commonly used functions is as follows sqlite3 open Opens specified database file If the database file does not already exist it is created sqlite3 close Closes a previously opened database file sqlite3 prepare v2 Prepares a SQL statement ready for execution sqlite3 step Executes a SQL statement previously prepared by the sqlite3 prepare v2 function sqlite3 column type Returns a data field from the results of a SQL retrieval operation where type is replaced by the data type of the data to be extracted text blob bytes int int16 etc sqlite3 finalize Deletes a previously prepared SQL statement from memory sqlite3 exec Combines the functionality of sqlite3 prepare v2 sqlite3 step and sqlite3 finalize into a single function call This of course represents only a small subset of the complete range of functions available with SQLite A full list can be found at http www sqlite org c3ref funclist html Declaring a SQLite Database Before any tasks can be performed on database it must first be declared To do so it is necessary to declare a variable that points to an instance of a structure of type sqlite3 the sqlite3 structure is defined in the sqlite3 h include file For example sqlite3 contactDB Declare a pointer to sqlite database structure Opening or Creating a Database Once declared a database file may be opened using the sqlite3 open function If the specified database file does

    Original URL path: http://www.techotopia.com/index.php/IPhone_Database_Implementation_using_SQLite (2016-02-13)
    Open archived version from archive


  • An Example SQLite based iPhone Application - Techotopia
    phone release status release super dealloc Creating the Database and Table When the application is launched it will need to check whether the database file already exists and if not create both the database file and a table within the database in which to store the contact information entered by the user The code to perform this task can be placed in the viewDidLoad method of our view controller class Select the databaseViewController m file scroll down to the viewDidLoad method and remove the comment markers from around it and Edit the code for this method as follows void viewDidLoad NSString docsDir NSArray dirPaths Get the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 Build the path to the database file databasePath NSString alloc initWithString docsDir stringByAppendingPathComponent contacts db NSFileManager filemgr NSFileManager defaultManager if filemgr fileExistsAtPath databasePath NO const char dbpath databasePath UTF8String if sqlite3 open dbpath contactDB SQLITE OK char errMsg const char sql stmt CREATE TABLE IF NOT EXISTS CONTACTS ID INTEGER PRIMARY KEY AUTOINCREMENT NAME TEXT ADDRESS TEXT PHONE TEXT if sqlite3 exec contactDB sql stmt NULL NULL errMsg SQLITE OK status text Failed to create table sqlite3 close contactDB else status text Failed to open create database filemgr release super viewDidLoad The code in the above method performs the following tasks Identifies the application s Documents directory and constructs a path to the contacts db database file Creates an NSFileManager instance and uses it to detect if the database file already exists If the file does not yet exists it converts the path to a UTF 8 string and creates the database via a call to the SQLite sqlite3 open function passing through a reference to the contactDB variable declared previously in the interface file Prepares a SQL statement to create the contacts table in the database Reports the success or failure of the operation via the status label Closes the database and performs a memory clean up Implementing the Code to Save Data to the SQLite Database The saving of contact data to the database is the responsibility of the saveData action method This method will need to open the database file extract the text from the three text fields and construct and execute a SQL INSERT statement to add this data as a record to the database Having done this the method will then need to close the database In addition the code will need to clear the text fields ready for the next contact to be entered and update the status label to reflect the success or otherwise of the operation In order to implement this behavior therefore we need to modify the template method created previously as follows void saveData sqlite3 stmt statement const char dbpath databasePath UTF8String if sqlite3 open dbpath contactDB SQLITE OK NSString insertSQL NSString stringWithFormat INSERT INTO CONTACTS name address phone VALUES name text address text phone text const char insert stmt insertSQL UTF8String sqlite3 prepare v2 contactDB insert stmt 1 statement NULL if sqlite3

    Original URL path: http://www.techotopia.com/index.php/An_Example_SQLite_based_iPhone_Application (2016-02-13)
    Open archived version from archive

  • Working with iPhone Databases using Core Data - Techotopia
    data object as though a relationship had been defined between those entities Fetched properties lack the flexibility of relationships and are referred to by Apple s Core Data documentation as weak one way relationships best suited to loosely coupled relationships Fetch request A predefined query that can be referenced to retrieve data objects based on defined predicates For example a fetch request can be configuring into an entity to retrieve all contact objects where the name field matches John Smith Persistent Store Coordinator google ADSDAQBOX FLOW google The persistent store coordinator is responsible for coordinating access to multiple persistent object stores As an iPhone developer you will never directly interact with the persistence store coordinator and in fact will very rarely need to develop an application that requires more than one persistent object store When multiple stores are required the coordinator presents these stores to the upper layers of the Core Data stack as a single store Persistent Object Store The term persistent object store refers to the underlying storage environment in which data are stored when using Core Data Core Data supports three disk based and one memory based persistent store Disk based options consist of SQLite XML and binary By default the iPhone SDK will use SQLite as the persistent store In practice the type of store being used is transparent to you as the developer Regardless of your choice of persistent store your code will make the same calls to the same Core Data APIs to manage the data objects required by your application Defining an Entity Description Entity descriptions may be defined from within the Xcode environment When a new project is created with the option to include Core Data a template file will be created named projectname xcdatamodel Double clicking on this file in the main Xcode project window will load the model into the entity editing environment as illustrated in the following figure Create a new entity by clicking on the button located at the button left of the Entity panel located in the top left hand corner of the window The new entity will appear in the list and the detail panel will display the settings for the new entity The graph area will also update to reflect the existence of the new entity where if nothing else the name at least should be changed to something more descriptive than the default To add attributes to the entity click on the button located in the bottom left hand corner of the Property panel located in the top center of the window and select Add Attribute from the resulting menu In the detail panel name the attribute and specify the type and any other options that are required Repeat the above steps to add more attributes and additional entities The Xcode entity environment also allows relationships to be established between entities Assume for example two entities named Contacts and Sales In order to establish a relationship between the two tables right click on the

    Original URL path: http://www.techotopia.com/index.php/Working_with_iPhone_Databases_using_Core_Data (2016-02-13)
    Open archived version from archive

  • An iPhone OS Core Data Tutorial - Techotopia
    and connect it to the application delegate Select the coreData entry from the top of the Groups Files list to display all the files in the project and scroll down to MainWindow xib Double click on this file to load it into the Interface Builder tool From the Library window drag and drop a View Controller object onto the MainWindow xib window Once released the new view controller should appear beneath the existing objects as illustrated in the following figure With the new view controller selected open the Identity Inspector window Tools Identity Inspector or Command 4 and change the Class value to coreDataViewController Display the Attributes page by selecting the far left toolbar button in the inspector window and assign coreDataViewController as the NIB file Finally establish a connection between the application delegate and the view controller This is achieved by ctrl clicking on the core Data App Delegate item in the MainWindow xib window dragging the resulting blue line to Core Data View Controller item in the same window and selecting viewController from the menu With the Core Data App Delegate item selected in the MainWindow xib file and the Connections Inspector displayed the settings should appear as shown in the following figure Save the file and exit from Interface Builder Now that we have a view controller programmed into our application we need to extend that class to include some actions and outlets Adding Actions and Outlets to the View Controller As with previous instances of our Contacts application our Core Data example will include a user interface that needs to accept and display name address and phone information and to react to the selection of a save and a find button In addition a status label will be used to provide the user with feedback To declare the outlets and actions associated with these user interface components select the coreDataViewController h file and modify the class declaration so that it reads as follows import UIKit UIKit h interface coreDataViewController UIViewController UITextField name UITextField address UITextField phone UILabel status property nonatomic retain IBOutlet UITextField name property nonatomic retain IBOutlet UITextField address property nonatomic retain IBOutlet UITextField phone property nonatomic retain IBOutlet UILabel status IBAction saveData IBAction findContact end Save the file then select the coreDataViewController m implementation file add an synthesize directive for the outlets and add template methods for the two declared actions import coreDataViewController h import coreDataAppDelegate h implementation coreDataViewController synthesize name address phone status void saveData void findContact end Once the changes are complete save the file before proceeding Designing the User Interface With the actions and outlets defined now is a good time to design the user interface and establish the connections To load the Interface Builder tool double click on the corewDataViewController xib file The user interface and corresponding connections used in this tutorial are the same as those in previous data persistence chapters The completed view should appear as follows Before saving the user interface design stretch the status label located

    Original URL path: http://www.techotopia.com/index.php/An_iPhone_OS_Core_Data_Tutorial (2016-02-13)
    Open archived version from archive

  • An Overview of iPhone Multitouch, Taps and Gestures - Techotopia
    the next responder in the response chain defined by the object s nextResponder property for further processing and so on up the chain If the first responder is not able to handle the event it will also pass it to the next responder in the chain and so on until it either reaches a responder that handles the event or it reaches the end of the chain the UIApplication object where it will either be handled or discarded Take for example a UIView with a UIButton subview If the user touches the screen over the button then the button as first responder will receive the event If the button is unable to handle the event it will need to be passed up to the view object If the view is also unable to handle the event it would then be passed to the view controller and so on When working with the responder chain it is important to note that the passing of an event from one responder to the next responder in the chain does not happen automatically If an event needs to be passed to the next responder code must be written to make it happen Forwarding an Event to the Next Responder An event may be passed on to the next responder in the response chain by calling the nextResponder method of the current responder passing through the method that was triggered by the event and the event itself Take for example a situation where the current responder object is unable to handle a touchesBegan event In order to pass this to the next responder the touchesBegan method of the current responder will need to make a call as follows void touchesBegan NSSet touches withEvent UIEvent event self nextResponder touchesBegan touches withEvent event Gestures Gesture is an umbrella term used to encapsulate any single interaction between the touch screen and the user between starting at the point that the screen is touched by one or more fingers and the time that the last finger leaves the surface of the screen Swipes pinches stretches and flicks are all forms of gesture Taps A tap as the name suggests occurs when the user touches the screen with a single finger and then immediately lifts it from the screen Taps can be single taps or multiple taps and the event will contain information about the number of times a user tapped on the screen Touches A touch occurs when a finger establishes contact with the screen When more than one finger touches the screen each figure registers as a touch up to a maximum of five fingers Touch Notification Methods Touch screen events cause one of four methods on the first responder object to be called The method that gets called for a specific event will depend on the nature of the interaction In order to handle events therefore it is important to ensure that the appropriate methods from those outlined below are implemented within your responder chain These methods

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_iPhone_Multitouch,_Taps_and_Gestures (2016-02-13)
    Open archived version from archive

  • An Example iPhone Touch, Multitouch and Tap Application - Techotopia
    code which in turn requires that three outlets be declared Select the touchViewController h file and modify it as follows import UIKit UIKit h interface touchViewController UIViewController UILabel touchStatus UILabel methodStatus UILabel tapStatus property nonatomic retain IBOutlet UILabel touchStatus property nonatomic retain IBOutlet UILabel methodStatus property nonatomic retain IBOutlet UILabel tapStatus end Save the file by selecting File Save or pressing Command S Having declared the outlets in the interface file edit the touchViewController m implementation file and add the corresponding synthesize directive import touchViewController h implementation touchViewController synthesize touchStatus methodStatus tapStatus end Having declared the outlets it is time to design the user interface Designing the user Interface Launch the Interface Builder tool by double clicking on the touchViewController xib file Within Interface Builder modify the user interface by adding label components and modifying properties until the view appears as follows When adding the labels to the right of the view be sure to stretch them so that they reach to the right hand edge of the view area Ctrl click on the File s Owner icon and drag the resulting blue line to the label adjacent to the Method label and select the methodStatus outlet from the resulting menu Repeat these steps to establish connections between the touchStatus and tapStatus outlets and the corresponding label objects Enabling Multitouch on the View google IOSBOX google By default views are configured to respond to only single touches in other words a single finger touching or tapping the screen at any one time For the purposes of this example we plan to detect multiple touches In order to enable this support it is necessary to change an attribute of the view object To achieve this click on the background of the View window display the Attribute Inspector window Tools Attribute Inspector or Command 1 and make sure that the Multiple Touch option is selection in the Interaction section at the bottom of the window Save the design and exit from Interface Builder Implementing the touchesBegan Method When the user touches the screen the touchesBegan method of the first responder is called In order to capture these event types we need to implement this method in our view controller In the main Xcode project window select the touchViewController m file and add the touchesBegan methods as follows void touchesBegan NSSet touches withEvent UIEvent event NSUInteger touchCount touches count NSUInteger tapCount touches anyObject tapCount methodStatus text touchesBegan touchStatus text NSString stringWithFormat d touches touchCount tapStatus text NSString stringWithFormat d taps tapCount This method obtains a count of the number of touch objects contained in the touches set essentially the number of fingers touching the screen and assigns it to a variable It then gets the tap count from one of the touch objects The code then updates the methodStatus label to indicate that the touchesBegan method has been triggered constructs a string indicating the number of touches and taps detected and displays the information on the touchStatus and tapStatus labels Implementing the touchesMoved

    Original URL path: http://www.techotopia.com/index.php/An_Example_iPhone_Touch,_Multitouch_and_Tap_Application (2016-02-13)
    Open archived version from archive

  • Detecting iPhone Touch Screen Gesture Motions - Techotopia
    of the touch and update these values in real time as the finger moves across the screen When the finger is lifted from the screen the start and end coordinates of the gesture will then be displayed This will require the creation of two outlets that will later be connected to labels within the user interface of the application In addition we need to add an instance variable to our view controller in which to store the start position of the touch To create these outlets and the instance variable select the touchMotionViewController h file and modify it as follows import UIKit UIKit h interface touchMotionViewController UIViewController UILabel xCoord UILabel yCoord CGPoint startPoint property retain nonatomic IBOutlet UILabel xCoord property retain nonatomic IBOutlet UILabel yCoord property CGPoint startPoint end Next edit the touchMotionViewController m file and add the synthesize directive import touchMotionViewController h implementation touchMotionViewController synthesize xCoord yCoord startPoint end Once the code changes have been implemented be sure to save both files before proceeding to the user interface design phase Designing the Application User Interface Double click on the touchMotionViewController xib file to load the NIB file into Interface Builder Within Interface Builder create a user interface such that it resembles the layout in the following figure Be sure to stretch the labels so that they both extend to cover most of the width of the view Once the label objects have been added to the view establish a connection between the xCoord outlet and the top label by Crtl clicking on the File s Owner and dragging the blue line to the top label Release the pointer and select xCoord from the resulting menu Repeat this step for the yCoord outlet and save the design before exiting from Interface Builder Implementing the touchesBegan Method When the user first touches the screen the location coordinates need to be saved in the startPoint instance variable and the coordinates reported to the user This can be achieved using the following code in the touchMotionViewController m file void touchesBegan NSSet touches withEvent UIEvent event UITouch theTouch touches anyObject startPoint theTouch locationInView self view CGFloat x startPoint x CGFloat y startPoint y xCoord text NSString stringWithFormat x f x yCoord text NSString stringWithFormat y f y Implementing the touchesMoved Method When the user user s finger moves across the screen the touchesMoved event will be called repeatedly until the motion stops By implementing the touchesMoved method in our view controller we can detect the motion and display the revised coordinates to the user void touchesMoved NSSet touches withEvent UIEvent event UITouch theTouch touches anyObject CGPoint touchLocation theTouch locationInView self view CGFloat x touchLocation x CGFloat y touchLocation y xCoord text NSString stringWithFormat x f x yCoord text NSString stringWithFormat y f y Implementing the touchesEnded Method When the user user s finger lifts from the screen the touchesEnded method of the first responder is called The final task therefore is to implement this method in our view controller such that it displays the

    Original URL path: http://www.techotopia.com/index.php/Detecting_iPhone_Touch_Screen_Gesture_Motions (2016-02-13)
    Open archived version from archive

  • Drawing iPhone 2D Graphics with Quartz - Techotopia
    work on the basis of points These are essentially the x and y coordinates of a two dimensional coordinate system on the device screen with 0 0 representing the top left hand corner of the display These coordinates are stored in the form of CGFloat variables An additional C structure named CGPoint is used to contain both the x and y coordinates to specify a point on the display Similarly the CGSize structure stores two CGFloat values designating the width and height of an element on the screen Further the position and dimension of a rectangle can be defined using the CGRect structure which contains a CGPoint the location and CGSize the dimension of a rectangular area Of key importance when working with points and dimensions is that these values do not correspond directly to screen pixels In other words there is not a one to one correlation between pixels and points Instead the underlying framework decides based on a scale factor where a point should appear and at what size relative to the resolution of the display on which the drawing is taking place This enables the same code to work on both higher and lower resolution screens without the programmer having to worry about it For more precise drawing requirements iOS version 4 and later allows the scale factor for the current screen to be obtained from UIScreen UIView UIImage and CALayer classes allowing the correlation between pixels and points to be calculated for greater drawing precision For iPhone OS 3 or older the scale factor is always returned as 1 0 The Graphics Context Almost without exception all Quartz API function calls require that the graphics context be passed as an argument Each view has its own context which is responsible for performing the requested drawing tasks and subsequently rendering those drawings onto the corresponding view The graphics context can be obtained with a call to the UIGraphicsGetCurrentContext function which returns a result of type CGContextRef CGContextRef graphics context UIGraphicsGetCurrentContext Working with Colors in Quartz 2D The Core Graphics CGColorRef data type is used to store colors when drawing with Quartz This data type holds information about the colorspace of the color RGBA CMYK or gray scale together with a set of component values that specify both the color and the transparency of that color For example the color red with no transparency would be defined with the RGBA components 1 0 0 0 0 0 1 0 A colorspace can be created via a Quartz API function call For example to create an RGB colorspace CGColorSpaceRef colorspace CGColorSpaceCreateDeviceRGB If the function fails to create a colorspace the function will return a NULL value In the case of a successful creation the colorspace must be released when no longer required via a call to the CGColorSpaceRelease function CGColorSpaceRelease colorspace Gray scale and CMYK color spaces may similarly be created using the CGColorSpaceCreateDeviceGray and CGColorSpaceCreateDeviceCMYK functions respectively Once the colorspace has been created the next task is to

    Original URL path: http://www.techotopia.com/index.php/Drawing_iPhone_2D_Graphics_with_Quartz (2016-02-13)
    Open archived version from archive



  •