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".
  • Using the UIPickerView and UIDatePicker Components in iOS 4 iPhone Applications - Techotopia
    a pre configured class designed specifically for the selection of dates and times The UIPickerView class on the other hand allows for the creation of custom picker controls and will explored in An iOS 4 iPhone UIPickerView Example A DatePicker Example By way of introduction to the concept of using pickers in an iOS 4 iPhone application we will begin with a very simple example that utilizes the UIDatePicker class The application will consist of a DatePicker a label and a button When the button is pressed by the user the date and time selected in the picker will be displayed on the label Begin by creating a new iOS iPhone project named datePicker using the View based Application template Once the main Xcode project window appears select the datePickerViewController h file modify it to add the outlets for the user interface objects and add a declaration for the action method to be called when the user touches the button import UIKit UIKit h interface datePickerViewController UIViewController UIDatePicker datePicker UILabel dateLabel property nonatomic retain IBOutlet UIDatePicker datePicker property nonatomic retain IBOutlet UILabel dateLabel IBAction getSelection end Once the modifications to the file are complete be sure to save the file before proceeding Designing the User Interface Double click on the datePickerViewController xib file to launch the Interface Builder tool Drag and drop the Date Picker Label and Button components from the Library window onto the view and modify and position the layout so that the view resembles the following figure google ADSDAQBOX FLOW google Note that the text of the label is centered and that it has been stretched to the outer margins of the containing view The configuration of the Date Picker object such as date format etc may be changed if desired via a variety of properties accessed by selecting the object in the view and displaying the Attributes Inspector Command 1 Establish connections between the outlet defined in the datePickerViewController h file and the Date Picker by Ctrl clicking on the File s Owner icon in the documents window and dragging the resulting line to the Date Picker object in the view window Release the pointer and select datePicker from the resulting menu Repeat this task to connect the dateLabel outlet to the Label object Finally select the button in the view window and display the Connections Inspector Command 3 Click in the circle to the right of the Touch Up Inside event and drag the line to the File s Owner entry From the resulting menu select the getSelection action method Save the design and exit from Interface Builder Coding the Date Picker Example Functionality Now that the outlets and user interface have been implemented it is time to write the functional code that will make the application work In actual fact the only method that needs to be implemented for this simple example is the getSelection action method that is called when the user touches the button In addition the synthesize directive for the two

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


  • An iOS 4 iPhone UIPickerView Example - Techotopia
    will need to make sure the keyboard is hidden when the user touches the Return key so an action method named textFieldReturn also needs to be declared to accommodate this requirement import UIKit UIKit h interface pickerViewController UIViewController UIPickerViewDelegate UIPickerViewDataSource UIPickerView picker NSArray countryNames NSArray exchangeRates UILabel resultLabel UITextField dollarText property nonatomic retain IBOutlet UIPickerView picker property nonatomic retain IBOutlet UILabel resultLabel property nonatomic retain IBOutlet UITextField dollarText property nonatomic retain NSArray countryNames property nonatomic retain NSArray exchangeRates IBAction textFieldReturn id sender end Save the file once the necessary changes have been made Designing the User Interface Within the main Xcode project window double click on the pickerViewController xib file to launch Interface Builder Drag and drop a UIPickerView from the Library onto the View window and position it at the bottom of the view Also add a label and text field Stretch the right and left hand edges of the label until the dotted blue margin line appears Using the Attribute Inspector Command 1 configure centered alignment on the label Select the text field and change the Placeholder setting in the Attribute Inspector to US Dollars USD Once completed the view should appear as illustrated in the following figure Ctrl click on the File s Owner entry in the documents window and drag the resulting line to the text field in the view After releasing the line select the dollarText outlet from the menu Repeat these steps to connect to picker and result outlets to the picker and label objects respectively Next select the PickerView component in the View window and display the Connections Inspector Command 2 Click in the round circle to the right of the dataSource outlet in the inspector window and drag the line to the File s Owner entry Repeat this task for the delegate outlet Finally select the text field object and click and drag from the circle to the right of the Did End On Exit event in the Connections Inspector to the File s Owner After releasing the mouse select the textFieldReturn action method from the resulting label The user interface is now designed and the outlets and action connected Save the design and exit from Interface Builder Initializing the Arrays The data that will be used in our application is stored in two arrays one for the country name and the other for the corresponding exchange rate In the real world the application would likely obtain uptodate exchange rate information from an external source but for the purposes of this example we will hard code the prevailing rates at the time of writing These arrays need to be initialized when the application loads so the necessary code should be added to the viewDidLoad method of the pickerViewController m file be sure to remove the comment markers and from around this method before adding the code Now is also a good time to add the appropriate synthesize directives import pickerViewController h implementation pickerViewController synthesize picker countryNames exchangeRates synthesize resultLabel dollarText void viewDidLoad

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

  • IOS 4 iPhone Directory Handling and File I/O – A Worked Example - Techotopia
    to the FileExampleViewController m Designing the User Interface As previously described our application is going to consist of a button and a text field To begin the user interface design process double click on the FileExampleViewController xib file to launch the Interface Builder tool Once the tool has started drag a UIButton and then a UITextField from the Library window Tools Library onto the view Double click on the button and change the text to Save Position the components and resize the width of the text field so that the layout appears as illustrated in the following figure The next step is to establish the connections between the user interface components and the action and outlet created in the view controller code Open the Connections Inspector window by selecting the Tools Connections Inspector menu option or by pressing Command 2 on the keyboard and select the button object in the view window so that the available events for that object are listed in the connections inspector window Click in the small circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner entry in the documents window Release the mouse button and select the saveText action method from the resulting menu to create the connection To connect the text field to the textBox outlet declared in the view controller interface file press and hold the control key click with the mouse over the File s Owner and drag the blue line to the text field object in the view window Release and select the textBox entry from the resulting menu The user interface design is complete and the connections are now established Save the design File Save and exit from Interface Builder Interface Builder Quit Interface Builder Checking the Data File on Application Startup Each time the application is launched by the user we need to check to see if the data file already exists if the user has not previously saved any text the file will not have been created If the file does exist the contents need to be read by the application and displayed within the text field A good place to put initialization code of this nature is in the viewDidLoad method of the view controller With this in mind select the FileExampleViewController m file and scroll down to the viewDidLoad method Remove the comment markers from around the method and edit it as follows Implement viewDidLoad to do additional setup after loading the view typically from a nib void viewDidLoad NSFileManager filemgr NSString dataFile NSString docsDir NSArray dirPaths filemgr NSFileManager defaultManager Identify the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 Build the path to the data file dataFile docsDir stringByAppendingPathComponent datafile dat Check if the file already exists if filemgr fileExistsAtPath dataFile Read file contents and display in textBox NSData databuffer databuffer filemgr contentsAtPath dataFile NSString datastring NSString alloc initWithData databuffer encoding NSASCIIStringEncoding textBox text datastring datastring release filemgr release super viewDidLoad

    Original URL path: http://www.techotopia.com/index.php/IOS_4_iPhone_Directory_Handling_and_File_I/O_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive

  • IOS 4 iPhone Data Persistence using Archiving - Techotopia
    IBAction saveData end Having made the appropriate declarations in the interface file the next step is to move to the archiveViewController m implementation file where we will synthesize the access methods for our instance variables and create a template method for the saveData action import archiveViewController h implementation archiveViewController synthesize name address phone dataFilePath void saveData end Next make sure that we free up memory that we have allocated when the application exists Releasing Memory Having allocted memory in implementing the above outlets it is important that we add code to free up any resources that were allocated during execution of the application To do so edit the archiveViewController m file again and modify the viewDidUnload and dealloc methods as follows void viewDidUnload Release any retained subviews of the main view e g self myOutlet nil self name nil self address nil self phone nil self dataFilePath nil void dealloc name release address release phone release dataFilePath release super dealloc We will need to do some more coding later but at this point it makes sense to design the user interface and establish the connections between the user interface object and the outlets and action we have declared so far Designing the iPhone User Interface The user interface for our application is going to consist of three UILabels three UITextFields and single UIButton Launch the Interface Builder tool by double clicking on the archiveViewController xib in the main Xcode project window Display the tool s Library window if it is not already visible by selecting the Tools Library menu option or by pressing Command L Drag drop resize position and configure objects on the View window canvas until your design approximates that illustrated in the following figure The next step is to establish the connections to our action and outlets Beginning with the outlets hold down the Ctrl key and click and drag from the File s Owner item in the documents window to the text field component located to right of the Name label object Release the Ctrl key and mouse button and select the name outlet from the resulting menu Repeat these steps for the address and phone text fields connecting them to the corresponding outlets To connect the action select the Save button object in the view window and display the Connections Inspector window Tools Connections Inspector or Command 2 Click with the mouse within the small round circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner entry in the documents window Release the mouse button and select the saveData method from the resulting window Having designed the user interface and established the necessary connections save the design and exit from Interface Builder Checking for the Existence of the Archive File on Startup Each time the application is launched by the user the code will need to identify whether the archive data file exists from a previous session In the event that it does exist the

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

  • IOS 4 iPhone Database Implementation using SQLite - Techotopia
    its documents directory the file will be located on the host system in the following folder Users user Library Application Support iPhone Simulator sdk version Applications id Documents Where user is the login name of the user running the iOS Simulator session sdk version is the version of the iOS SDK used to build the application and id is the unique ID of the application Preparing an iOS 4 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 declarations 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

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

  • An Example SQLite based iOS 4 iPhone Application - Techotopia
    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 before editing 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 subsequently uses it to detect if the database file already exists If the file does not yet exist the code 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 step statement SQLITE DONE status text Contact added name text address text phone text else status text Failed to add contact sqlite3 finalize statement sqlite3 close contactDB The next step in our application development process is to implement the action for the find button Implementing Code

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

  • Working with iOS 4 iPhone Databases using Core Data - Techotopia
    to be accessed from another 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 iOS 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 iOS 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

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

  • An iOS 4 iPhone Core Data Tutorial - Techotopia
    in later steps Connecting the View The next step is to add the new view controller to the project associate it with the view NIB file 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 coreData 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 CoreData App Delegate Controller 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 import the coreDataAppDelegate h file 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 coreDataViewController xib file The user interface and corresponding connections used in

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



  •