<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iDevKit &#187; iPhone SDK (Official Dev)</title>
	<atom:link href="http://idevkit.com/iphonedev/category/iphone-sdk/feed/" rel="self" type="application/rss+xml" />
	<link>http://idevkit.com/iphonedev</link>
	<description>An iPhone Developer&#039;s Blog</description>
	<lastBuildDate>Sat, 24 Apr 2010 17:47:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Saving NSMutableArrays</title>
		<link>http://idevkit.com/iphonedev/2009/09/saving-nsmutablearrays/</link>
		<comments>http://idevkit.com/iphonedev/2009/09/saving-nsmutablearrays/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 23:44:25 +0000</pubDate>
		<dc:creator>sj</dc:creator>
				<category><![CDATA[iPhone SDK (Official Dev)]]></category>

		<guid isPermaLink="false">http://idevkit.com/iphonedev/?p=134</guid>
		<description><![CDATA[Good day lads and lasses of the internet, I decided that saving data files for your applications is an important one to know and saving objects in an NSMutableArray wants you to occasionally make you gouge your eyes out until you get the system lined up pretty well.  Let us start with the order [...]]]></description>
			<content:encoded><![CDATA[<p>Good day lads and lasses of the internet, I decided that saving data files for your applications is an important one to know and saving objects in an NSMutableArray wants you to occasionally make you gouge your eyes out until you get the system lined up pretty well.  Let us start with the order of events here for saving and loading.  <strong>Create and NSMutableArray with your object -&gt; Locate the directory and the file to save to -&gt; Encode the array into an NSMutableData file -&gt; Store the NSMD in the given directory</strong> Simple enough.  For loading, its really the same  system just backward I guess you could say.  We&#8217;ll go into that a little bit later.  For now, <strong>Open Xcode -&gt; New Project -&gt; &#8220;View Based Application&#8221; -&gt; &#8220;New File&#8221; -&gt; &#8220;Objective-C Class&#8221; -&gt; Call it theFile and check the box for a header file</strong>.  At this point, I am going to expect you all to know how to do some of these remedial tasks.  Go to your header for this new file and declare two <code>NSString</code>s along with their <code>@property/@synthesize</code> declarations at the end of the header and start of the <code>@implementation</code>.  This is the object that we are going to toss into our <code>NSSMutableArray</code> later, which means we are going to have to conform to some protocols designated by the foundation framework.  Let us assume you called your two <code>NSString</code>s <code>textField</code> and <code>numberField</code> (mainly because that is how I named them in the sample code, there are a few treats in there that use styles and all for text fields etc that weren&#8217;t mentioned before).  We will need to implement both the <code>encoder</code> and <code>decoder</code> methods here and thats it.  Add the following code to the implementation of <code>theFile</code>:</p>
<pre>- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:textField forKey:@"text"];
    [encoder encodeObject:numberField forKey:@"number"];
}

-(void)initWithCoder:(NSCoder *)coder {
	textField = [[coder decodeObjectForKey:@"text"] retain];
	numberField = [[coder decodeObjectForKey:@"number"] retain];
}</pre>
<p>First off is the <code>encode</code> protocol, all we are doing here is encoding the two strings inside of the <code>theFile</code> and giving them a reference string so that we can locate them later.  The other method does the opposite of that, it decodes both objects for the given keys and stores them in those strings.  With that, we can move on to the quick user interface I wrote for this.  We are going to want two <code>UITextField</code>s to control the content of the strings in our custom object, two <code>UIButtons</code> to save and load the data, and a <code>UILabel</code> to display the loaded contents.  Same thing as we did in our previous tutorial that introduced our world of iDevKit to the <code>UITextField</code>, <code>UILabel</code>, and <code>UIButton</code>, which can be found <a title="UITextFields and UIButtons" href="http://idevkit.com/iphonedev/2009/09/uitextfields-and-uibuttons/" target="_blank">here</a>.  I will give you the set up code here for all the UI today but this will probably be the last time until something new is tutorialized.  Add the <code>UITextField</code>s to the header of your viewController class (<code>labelField, numberField<code>UIButtons</code> (<code>saveItems, loadItems<code>theFile *value;</code>.</code></code></p>
<pre>- (void)loadView {
     CGRect frame = [UIScreen mainScreen].applicationFrame;
     UIView *view = [[UIView alloc] initWithFrame:frame];
     self.view = view;

     displayLoad = [[UILabel alloc] initWithFrame:CGRectMake(10,140,300,28)];
     displayLoad.font = [UIFont fontWithName:@"Arial" size:16];

     [self saveItems];
     [self loadItems];
     [self labelField];
     [self numberField];
     [self.view addSubview:saveItems];
     [self.view addSubview:loadItems];
     [self.view addSubview:labelField];
     [self.view addSubview:numberField];
     [self.view addSubview:displayLoad];
}

-(UIButton *)saveItems {
     saveItems = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
     saveItems.frame = CGRectMake(50,222,90,45);
     [saveItems setTitle:@"Save" forState:UIControlStateNormal];
     [saveItems setTitle:@"Save" forState:UIControlStateHighlighted];
     [saveItems setTitleColor:[UIColor colorWithRed:0.0 green:0.3 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
     [saveItems setTitleColor:[UIColor colorWithRed:0.0 green:0.1 blue:1.0 alpha:1.0] forState:UIControlStateHighlighted];
     [saveItems setBackgroundColor:[UIColor clearColor]];
     [saveItems addTarget:self action:@selector(saveObjects) forControlEvents:UIControlEventTouchUpInside];

     return saveItems;
}

-(UIButton *)loadItems {
     loadItems = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
     loadItems.frame = CGRectMake(180,222,90,45);
     [loadItems setTitle:@"Load" forState:UIControlStateNormal];
     [loadItems setTitle:@"Load" forState:UIControlStateHighlighted];
     [loadItems setTitleColor:[UIColor colorWithRed:0.0 green:0.3 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
     [loadItems setTitleColor:[UIColor colorWithRed:0.0 green:0.1 blue:1.0 alpha:1.0] forState:UIControlStateHighlighted];
     [loadItems setBackgroundColor:[UIColor clearColor]];
     [loadItems addTarget:self action:@selector(loadObjects) forControlEvents:UIControlEventTouchUpInside];

     return loadItems;
}

-(UITextField *)labelField {
     if (labelField == nil) {
          CGRect frame = CGRectMake(20,100,280,30);
          labelField = [[UITextField alloc] initWithFrame:frame];

          labelField.borderStyle = UITextBorderStyleRoundedRect;
          labelField.textColor = [UIColor blackColor];
          labelField.font = [UIFont systemFontOfSize:17.0];
          labelField.placeholder = @"Type Something...";
          labelField.backgroundColor = [UIColor clearColor];
          labelField.autocorrectionType = UITextAutocorrectionTypeNo;

          labelField.keyboardType = UIKeyboardTypeDefault;
          labelField.returnKeyType = UIReturnKeyDone;

          labelField.clearButtonMode = UITextFieldViewModeWhileEditing;

          labelField.tag = 1;

          labelField.delegate = self;
     }
     return labelField;
}

-(UITextField *)numberField {
     if (numberField == nil) {
          CGRect frame = CGRectMake(20,50,280,30);
          numberField = [[UITextField alloc] initWithFrame:frame];

          numberField.borderStyle = UITextBorderStyleRoundedRect;
          numberField.textColor = [UIColor blackColor];
          numberField.font = [UIFont systemFontOfSize:17.0];
          numberField.placeholder = @"Numbers...";
          numberField.backgroundColor = [UIColor clearColor];
          numberField.autocorrectionType = UITextAutocorrectionTypeNo;

          numberField.keyboardType = UIKeyboardTypeNumberPad;
          numberField.returnKeyType = UIReturnKeyDone;

          numberField.clearButtonMode = UITextFieldViewModeWhileEditing;

          numberField.tag = 1;	

          numberField.delegate = self;
     }
     return numberField;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
     [textField resignFirstResponder];
     return YES;
}</pre>
<p>Not going to reinvent the wheel here so if you have any questions, consult the project I attach to the end of this or previous tutorials, there is <strong>NOTHING NEW</strong>.  Alrighty then, notice that the <code>UIButtons</code> send us to two separate methods: <code>saveObjects</code> and <code>loadObjects</code>.  Let us start with saving:</p>
<pre>-(void)saveObjects {
	value = [[theFile alloc] init];
	value.textField = labelField.text;
	value.numberField = numberField.text;

	NSMutableArray *array = [NSMutableArray arrayWithObjects:value,nil];
	NSMutableData *data = [NSMutableData data];
	NSKeyedArchiver *encode = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

	NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *docDirectory = [path objectAtIndex:0];
	NSString *file = [docDirectory stringByAppendingPathComponent:@"save.iDK"];
	NSLog(file);

	[encode encodeObject:array forKey:@"save"];
	[encode finishEncoding];

	[data writeToFile:file atomically:YES];
	[encode release];
}</pre>
<p>Okay then&#8230; First three lines are going to allocate/initialize an instance of <code>theFile</code> and set both of the strings inside of it to the values set in our <code>UITextField</code>s.  After that, we create an <code>NSMutableArray</code> and store <code>value</code> inside of it, where <code>nil</code> denotes the end of the array.  We then create a data file that will later house our array, we use <code>NSMutableData</code> for this.  Then we declare an <code>NSKeyedArchiver</code> that will be used in encoding our data file.  Now comes a really important step: locating our save directory.  This part I just kind of pulled as stock code from Apple but I will do my best to tell you what is going on.  The first line there finds us our local path to our app, then it finds the contained Documents directory.  We then extract the string from the array that will then be used to place our <code>file</code><code>NSLog()</code> here so we can find our application directory for the simulator if we are so inclined.  Few more steps: we encode our NSMA and to a reference point for later and push the encoding along.  After that, we write the <code>data</code> to our <code>file</code>, clean memory, and we are saved!  Almost done, now to add in our decoder bit, add our <code>loadObjects</code> method and lets begin.</p>
<pre>-(void)loadObjects {
	NSFileManager *manager = [NSFileManager defaultManager];

	NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *docDirectory = [path objectAtIndex:0];
	NSString *file = [docDirectory stringByAppendingPathComponent:@"save.iDK"];

	if([manager fileExistsAtPath:file]) {
		NSLog(@"file located and reading");

		NSMutableData *data;
		NSMutableArray *array;
		NSKeyedUnarchiver *decode;
		NSString *label;

		if(!value)	value = [[theFile alloc] init];

		data = [NSData dataWithContentsOfFile:file];
		decode = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
		array = [decode decodeObjectForKey:@"save"];
		[decode finishDecoding];
		[decode release];
		value = [array objectAtIndex:0];

		label = value.textField;
		label = [label stringByAppendingString:value.numberField];

		displayLoad.text = label;
	} else {
		NSLog(@"file not found, save something to create the file");
	}
}</pre>
<p>First up is we create what is called an <code>NSFileManager</code> and we set the value of this instance to <code>defaultManager</code>; in a nutshell, this is just creating an object that we will later use to look for a file and return a boolean value on whether or not it exists.  After that we do like we did before in the saving method and locate our file&#8217;s directory and name (not to be confused with the file itself, this just tells the device where the file SHOULD exist and what it SHOULD be called if it does exist).  Now we use a simple <code>if-else</code> statement that uses our <code>manager</code> to check to see if our file located at <code>file</code> exists, and if so, it will load it, if not, it sends an error message to the console and ends the method.  Let us assume it exists, otherwise its just boring and you won&#8217;t learn anything.  To start with we will declare the same variables we did while saving, with exception to the <code>NSKeyedArchiver</code>, which we replaced with the inverse: <code>NSKeyedUnarchiver</code>.  We also put in an <code>NSString</code> to store the displayed string in later.  The next line checks to see whether or not we have already allocated <code>value</code>, and if not, then we allocate it, simple &#8217;nuff.  We now pull the <code>NSMutableData</code> file from our Documents directory that we proved existed, and store it in <code>data</code>.  We decode the data file from there using our unarchiver and search for an <code>NSMutableArray</code> inside it using the key that we archived with before.  We push the decoder along while we store the array in <code>array</code>, clean the memory a little, and pull the first value from the array and store it in <code>value</code>.  From here is all cosmetic, we take the two strings in our new object, combine them, and set the <code>UILabel</code> text to it.</p>
<p><img class="alignleft size-full wp-image-152" title="B&amp;G Final" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Picture-43.png" alt="B&amp;G Final" width="72" height="53" /></p>
<p>Thats about it, if you have any questions just ask, you can find the source code <a title="Source Code for Saving Tutorial" href="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/iDK-Saving.zip">here</a>.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto; border: 0px initial initial;" title="User Interface" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Picture-2-199x300.png" alt="User Interface" width="199" height="300" /><br />
<img style="display: block; margin-left: auto; margin-right: auto; border: 0px initial initial;" title="Saving Console" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Picture-31.png" alt="Saving Console" width="652" height="308" /></p>
<p>Regards,</p>
<p>Sj</p>
]]></content:encoded>
			<wfw:commentRss>http://idevkit.com/iphonedev/2009/09/saving-nsmutablearrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UITextFields and UIButtons</title>
		<link>http://idevkit.com/iphonedev/2009/09/uitextfields-and-uibuttons/</link>
		<comments>http://idevkit.com/iphonedev/2009/09/uitextfields-and-uibuttons/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 00:14:17 +0000</pubDate>
		<dc:creator>sj</dc:creator>
				<category><![CDATA[iPhone SDK (Official Dev)]]></category>

		<guid isPermaLink="false">http://idevkit.com/iphonedev/?p=90</guid>
		<description><![CDATA[Hi again everyone, sorry for the late update, I have been pretty busy with another project for the blog this past week, along with a few other jobs/projects unrelated to this.  I still have yet to finish that other tutorial so I thought I would throw something together today that most of you guys will [...]]]></description>
			<content:encoded><![CDATA[<p>Hi again everyone, sorry for the late update, I have been pretty busy with another project for the blog this past week, along with a few other jobs/projects unrelated to this.  I still have yet to finish that other tutorial so I thought I would throw something together today that most of you guys will find relatively helpful (I hope).  So here we have it, a little tutorial that covers labels (nothing new at all here), textfields, buttons, and NSUserDefaults.  Alright, lets begin, open Xcode and create a new View Based Application, name it TextInput.</p>
<p>Navigate to TextInputViewController.h and you will need to declare the UITextFieldDelegate protocol by adding <code>&lt;UITextFieldDelegate&gt;</code> after <code>TextInputViewController : UIViewController</code>, this will tell your program that it needs to conform to the UITextFieldDelegate protocol, which in turn, allows you to create UITextFields.  Now, in the @interface section, declare two UILabels, two UITextFields, and two UIButtons like so:</p>
<pre>UILabel *firstLbl;
UILabel *lastLbl;
UITextField *firstName;
UITextField *lastName;
UIButton *saveBtn;
UIButton *loadBtn;,</pre>
<p>Under that, make sure to add the following code outside of the brackets but before the <code>@end</code>, this will let you control the UIButtons and UITextFields:</p>
<pre>@property(nonatomic,retain) UITextField *firstName;
@property(nonatomic,retain) UITextField *lastName;
@property(nonatomic,retain) UIButton *saveBtn;
@property(nonatomic,retain) UIButton *loadBtn;</pre>
<p>Now, go to your TextInputViewController.m and uncomment the <code>loadView</code> method.  Create a UIView now to fit the frame of the screen and set it to the <code>self.view</code>:</p>
<pre>CGRect frame = [UIScreen mainScreen].applicationFrame;
UIView *view = [[UIView alloc] initWithFrame:frame];
self.view = view;</pre>
<p><strong>NOTE: This is the last time I will be explaining how to create the viewController&#8217;s main view, same goes with generic labels that we will be using a lot, which will follow</strong><br />
From here, we need to prepare and initialize all of your views and objects that we will be using in the main viewController.  Starting with the labels:</p>
<pre>firstLbl = [[UILabel alloc] initWithFrame:CGRectMake(20,10,320,32)];
lastLbl = [[UILabel alloc] initWithFrame:CGRectMake(20,70,320,32)];
firstLbl.backgroundColor = [UIColor clearColor];
lastLbl.backgroundColor = [UIColor clearColor];</pre>
<p>This is simple, we are preparing the UILabels for the loaded data that we will be accessing later.  I didn&#8217;t bother setting any other properties for these labels, this isn&#8217;t a UILabel tutorial, I covered more of that in the <a title="iDevKit - Hello World" href="http://idevkit.com/iphonedev/2009/09/xcode-and-the-iphone-sdk/" target="_blank">Hello World tutorial </a>a couple of weeks ago.  After that, we get into the new stuff, the fun stuff.  You will need to start by creating a method that looks something like this:</p>
<pre>- (UITextField *) firstName {
     if(firstName == nil) {
          CGRect frame = CGRectMake(20,40,280,30);
          firstName = [[UITextField alloc] initWithFrame:frame];

          firstName.borderStyle = UITextBorderStyleRoundedRect;
          firstName.textColor = [UIColor blackColor];
          firstName.font = [UIFont systemFontOfSize:17.0];
          firstName.placeholder = @"First Name...";
          firstName.autocorrectionType = UITextAutoCorrectionTypeNo;

          firstName.keyboardType = UIKeyboardTypeDefault;
          firstName.returnKeyType = UIReturnKeyDone;

          firstName.clearButtonMode = UITextFieldViewModeWhileEditing;

          firstName.delegate = self;
     }
     return firstName;
}</pre>
<p>Alright, there are a <strong>LOT</strong> of new concepts here, all of which pertaining to setting up your customized UITextField, we will be using this again in a moment.  First off, we have an <code>if</code> statement that checks to see if the text field has already been allocated and initialized, if the <code>firstName</code> returns a <code>nil</code> value, then the enclosed statements are executed, if it doesn&#8217;t, then it just returns the already allocated UITextField.  Assuming that the statement was satisfied, lets step through all of the properties of the text field.  Like with most of the <code>UIKit</code> objects, you need to set the text field inside of a frame using the <code>CGRectMake</code> method.  We initialize <code>firstName</code> with this frame.  Then we set the <code>borderStyle</code>, this is what the frame of the field will look like, I used the <code>UITextBorderStyleRoundedRect</code> style here, which, like it says, makes the frame rounded on the corners.  <code>textColor</code> sets the input text&#8217;s color and <code>font</code> sets the font size of that input, similar to that used in a UILabel.  We use <code>placeholder</code> to fill the UITextField with a background text until it is touched and/or has any input.  <code>autocorrectionType</code> sets whether or not to use the iPhone&#8217;s auto-correct dictionary with input, I set this to no for proof and practice, the default is YES.  The <code>keyboardType</code> and <code>returnKeyType</code> properties delegate the keyboard settings, the first sets it to the standard keyboard and the latter sets the return key to say <code>Done</code> and to dismiss the keyboard.  Almost done, <code>clearButtonMode</code> property tells us whether or not to use the little gray &#8216;X&#8217; that clears the field.  Finally, <code>delegate</code> tells the text field that it is being controlled by this particular view controller.  We return the UITextField now at the end.</p>
<p>We use this method form again for the <code>lastName</code>, replacing <code>firstName</code> with <code>lastName</code> and changing any properties based on what you want to play with.  Remember, hit <code>Esc</code> on your keyboard to list the available options for each property after the &#8216;=&#8217; sign.</p>
<p>Add the following code to dismiss the keyboard when <code>Done</code> is clicked:</p>
<pre>- (BOOL) textFieldShouldReturn:(UITextField *)textField {
     [textField resignFirstResponder];
     return YES;
}</pre>
<p>Now we need to start setting up the buttons that save and load the data:</p>
<pre>- (UIButton *) saveBtn {
     saveBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
     saveBtn.frame = CGRectMake(0,0,90,45);
     [saveBtn setTitle:@"Save" forState:UIControlStateNormal];
     [saveBtn setTitle:@"Save" forState:UIControlStateHighlighted];
     [saveBtn setTitleColor:[UIColor colorWithRed:0.0 green:0.3 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
     [saveBtn setTitleColor:[UIColor colorWithRed:0.0 green:0.1 blue:1.0 alpha:1.0]  forState:UIControlStateHighlighted];
     [saveBtn setBackgroundColor:[UIColor clearColor]];
     [saveBtn addTarget:self action:@selector(saveText) forControlEvents:UIControlEventTouchUpInside];
     return saveBtn;
}</pre>
<p>Alrighty then, same idea as the UITextField method, we are just setting a group of properties for the UIButton.  First we set the type of button we want to <code>UIButtonTypeRoundedRect</code> and <code>retain</code> the view.  Next is the <code>frame</code> as always, the x,y coordinates are set to 0 because frankly, I prefer to set the location of UIButtons using the center point, which I will show later.  Button&#8217;s titles and images etc are based off of the <code>UIControlState</code> of the button.  First, we set the <code>title</code> of the button at its <code>UIControlStateNormal</code>, in this case it just says &#8220;Save&#8221;; we use the same statement again below, except using <code>UIControlStateHighlighted</code>, this sets the title of the button when it is clicked down.  We set the <code>titleColor</code> now for both states to a custom UIColor value, followed by the <code>backgroundColor</code> property, which makes the outside of the frame meld with the background&#8217;s color or image.  Finally, the most important bit of code is the <code>addTarget:action:forControlEvents:</code> that tells the program to execute the method <code>saveText</code> inside of <code>self</code> when the user performs a <code>UIControlEventTouchUpInside</code>, aka a touch of the button.  We return the button and continue.</p>
<p>Do this again with loadBtn, only this time make sure to change that second to last line to:</p>
<pre>[loadBtn addTarget:self action:@selector(loadText) forControlEvents:UIControlEventTouchUpInside];</pre>
<p>Configure it how ever you wish and play around with the properties, the best way to learn how to program is trial by error.</p>
<p>Now before we put this all together in our <code>loadView</code> method, we have two more bits of code to write, and these will be the ones the let us save and load our data: <code>saveText</code> and <code>loadText</code>.  Let us start with the first one, insert the following code after the UITextField and UIButton methods:</p>
<pre>[[NSUserDefaults standardUserDefaults] setObject:firstName.text forKey:@"firstName"];
[[NSUserDefaults standardUserDefaults] setObject:lastName.text forKey:@"lastName"];
[[NSUserDefaults standardUserDefaults] synchronize];
firstName.text = @"";
lastName.text = @"";</pre>
<p>Alright, new concept here: <code>NSUserDefaults</code>.  This is the Foundation Frameworks method of saving the default settings for a program along with other bits of data.  The first two methods are essentially identical, you start by calling <code>standarUserdefaults</code> which tells the next commands to look in the standard library of saved data.  Next, we need to save the string from the UITextField, which is done by using <code>setObject:</code> and then the string, which is the <code>text</code> property of your text field, and finally, we need to tell the computer where exactly to look when we want to load this, so we set <code>forKey:</code> to the name of the variable.  <strong>NOTE: I usually do it this way as an organizational method but you can set the <code>forKey</code> to whatever you want.  Also, if you poke around through the documentation from Apple, you can get the methods to save other types of data.</strong> Last new bit of code here is the <code>synchronize</code> method, which tells the program to pretty much save and do so now.  If you do not use this, when you are saving larger bits of data there is a chance that it does not save before the application is exited, at which point you can lose an entire saved game, as was the case with an error I was having on an application I wrote a while back.  Nothing new after that, these two calls just clear the text fields, I used this as a little visual aid to indicate that something actually happened.</p>
<p>Okay, almost done&#8230; now we just need to tell the program just how to load the data that we previously saved.  Add:</p>
<pre>NSString *first = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"];
NSString *last = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastName"];
firstLbl.text = first;
lastLbl.text = last;
[first release];
[last release];</pre>
<p>Alright, just the normal NSString declartaion/allocation/initialization is used here, we all know how to use that, the new part comes with the string that we are initializing the variable with.  We do as we did before and tell NSUserDefaults to use the <code>standardUserDefaults</code>, then we tell it to load the object that has a matching key to the one we put after <code>objectForKey</code>, if there is an object there, it loads it, if not, nothing happens, simple as that.  We do the same thing again only loading a different object this time.  <strong> NOTE: I am relatively sure that you can use <code>stringForKey:</code> instead although I have never had a reason to so play with it as you will.</strong> Now we place those strings inside of the UILabels, release the retained memory from the strings and move on to the last little thing, putting it all in play.  Back to the <code>loadView</code> method, insert:</p>
<pre>[self firstName];
[self lastName];
[self saveBtn];
[self loadBtn];
[saveBtn setCenter:CGPointMake(100,200)];
[loadBtn setCenter:CGPointMake(220,200)];
[self.view addSubview:firstName];
[self.view addSubview:lastName];
[self.view addSubview:saveBtn];
[self.view addSubview:loadBtn];
[self.view addSubview:firstLbl];
[self.view addSubview:lastLbl];</pre>
<p>This is what makes everything activate and come alive.  The first 4 lines execute your button and text field methods that initialze and allocate them with your custom settings.  The following two set the center of the buttons to exactly where I want them, I find this easier for most subviews.  The last 6 lines add everything to the superview.  That is it, make sure that you <code>release</code> everything that you retained in the <code>dealloc</code> method, <strong>Build &amp; Go</strong>.</p>
<div id="attachment_126" class="wp-caption aligncenter" style="width: 400px"><img class="size-full wp-image-126" title="Final Version" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Picture-41.png" alt="I changed the background color the same way we did in Hello World" width="390" height="738" /><p class="wp-caption-text">I changed the background color the same way we did in Hello World</p></div>
<p>That is all for now, you can get the sample code <a title="TextInput Source" href="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/iDK-TextInput.zip">here</a>.</p>
<p>Regards,<br />
sj</p>
]]></content:encoded>
			<wfw:commentRss>http://idevkit.com/iphonedev/2009/09/uitextfields-and-uibuttons/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Xcode and the iPhone SDK</title>
		<link>http://idevkit.com/iphonedev/2009/09/xcode-and-the-iphone-sdk/</link>
		<comments>http://idevkit.com/iphonedev/2009/09/xcode-and-the-iphone-sdk/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 02:55:58 +0000</pubDate>
		<dc:creator>sj</dc:creator>
				<category><![CDATA[Xcode]]></category>
		<category><![CDATA[iPhone SDK (Official Dev)]]></category>
		<category><![CDATA[intro]]></category>
		<category><![CDATA[sdk]]></category>

		<guid isPermaLink="false">http://idevkit.com/iphonedev/?p=8</guid>
		<description><![CDATA[Alright everyone, for the first tutorial on iDevKit, I though we should start somewhere relatively basic, and seeing as how this blog is going to be covering everything from Archiving to OpenGL, Quartz to GameKit, and CoreLocation to Cocoa Touch, I thought it would be best to start somewhere simple.  That is why this post [...]]]></description>
			<content:encoded><![CDATA[<p>Alright everyone, for the first tutorial on iDevKit, I though we should start somewhere relatively basic, and seeing as how this blog is going to be covering everything from Archiving to OpenGL, Quartz to GameKit, and CoreLocation to Cocoa Touch, I thought it would be best to start somewhere simple.  That is why this post will cover the hows and whys of Xcode, the IDE for the iPhone and Mac OS X, and make your very own &#8220;Hello World&#8221; using Objective-C.</p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-60" title="Xcode Logo" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/xcode-logo.png" alt="Xcode Logo" width="125" height="125" /></p>
<p>To start with, you will need the iPhone SDK (Xcode), available <a title="Apple Developer Connection" href="http://developer.apple.com/iphone/index.action" target="_blank">here</a>. Download the latest version, which is currently 3.0 for unregistered users, and 3.1 beta3 for certified developers (To become a certified developer, you have to <a title="iPhone Developer Enrollment" href="http://developer.apple.com/iphone/program/start/register/" target="_blank">enroll</a> with the Apple Developer Connection&#8217;s iPhone program. I will cover some hurdles related to this in a later post).  After you have downloaded the SDK, mount the dmg file and install. (This part is fairly straight forward)</p>
<p>After you have installed the iPhone SDK, open Xcode and select <strong>File -&gt; New Project</strong>.</p>
<div id="attachment_24" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-24" title="Xcode Intro-1.1" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Xcode-Intro-1.1-300x247.png" alt="Project Types" width="300" height="247" /><p class="wp-caption-text">Project Types</p></div>
<div id="attachment_25" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-25" title="Xcode Intro-1.2" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Xcode-Intro-1.2-300x99.png" alt="File Name" width="300" height="99" /><p class="wp-caption-text">File Name</p></div>
<p>When you&#8217;re there, you will be prompted with an array of options and templates to choose from for both Mac OS X and iPhone OS.  You will see six different options, but for this particular example, we will only concern ourselves with &#8220;View-Based Application&#8221;.  Select <strong>View-based Application</strong> and click <strong>Choose. . .</strong>, name your project &#8220;Hello World&#8221;, and a new window will then open, containing your application template.</p>
<div id="attachment_23" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-23" title="Xcode Intro-1.3" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Xcode-Intro-1.3-300x207.png" alt="New Project in Xcode" width="300" height="207" /><p class="wp-caption-text">New Project in Xcode</p></div>
<p>Here, you&#8217;re going to see many different file references and directories.  I&#8217;ll quickly go over what&#8217;s important:</p>
<p><strong>Classes</strong> &#8211; In here you will find your application delegate and root view controller, with appropriate headers.</p>
<p><strong>Other Sources</strong> &#8211; This contains the .pch (project header) that imports UIKit and Foundation Frameworks, along with the main.m file.</p>
<p><strong>Resources</strong> &#8211; As of now, this contains the XIB files (for Interface Builder), and the HelloWorld-Info.plist. XIBs are static files used to create UIViewControllers. The Info plist contains the core settings of your application like icon location, opening orientation, Bundle Names, Identifiers, etc. Much of this is used by Apple when releasing your application on App Store via iTunesConnect (much on this &#8220;fun&#8221; process later)</p>
<p><strong>Frameworks</strong> &#8211; This contains references to dynamic frameworks, including UIKit, Foundation, and CoreGraphics, with many more available on your system from the SDK.  This is also where static frameworks are stored, these frameworks are compiled into your application vs being linked to a dynamic framework present on the device.</p>
<p><strong>Products</strong> &#8211; This contains the executable .app that you get after compilation.</p>
<p>Everything else listed here is either organization, compiling information, or other components that we will worry about in the future.</p>
<p>For now, we are going to concern ourselves with the <strong>Classes</strong> section only.  We will be using an NSString to store text, a UILabel to display the string of text, and colored background.  So let us begin by editing the HelloWorldAppDelegate.m, insert the following line of code at the start of the applicationDidFinishLaunching: method:</p>
<p><code>[window setBackgroundColor:[UIColor blueColor]];</code></p>
<p>This will make the background of your application blue as opposed to the boring default white.  There is a host of preset colors in the UIColor API, along with methods that let you create your own by setting the RGB properties.</p>
<p>Now go to your HelloWorldViewController.m file and navigate to the loadView method and uncomment it.  This method will contain the code that loads your UILabel, NSString, and UIView.  Insert the following:</p>
<p><code>CGRect appFrame = [UIScreen mainScreen].applicationFrame;<br />
UIView *view = [[UIView alloc] initWithFrame:appFrame];<br />
self.view = view;</code></p>
<p>Okay, let me explain: <code>appframe</code> is essentially just a rectangle the size of your device screen (320px by 480px), which is used by <code>view</code> to set the frame it is built around.  <code>view</code> then becomes the layer that the rest of the ViewController uses to display other &#8220;subviews&#8221; (like UIImageView, UILabel, UIButton etc).  Now we are going to add our NSString (the object that will contain our text for the UILabel).  Below what we just added, type the following:</p>
<p><code>NSString *hello_text = [NSString stringWithFormat:@"Hello, World!"];</code></p>
<p>This line creates and initializes the object <code>hello_text</code> with the text that we will be using next.  Now type below this:</p>
<p><code>UILabel *hello_label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,30)];<br />
[hello_label setFont:[UIFont fontWithName:@"Arial" size:30]];<br />
[hello_label setCenter:CGPointMake(160,100)];<br />
[hello_label setText:hello_text];<br />
[hello_label setTextColor:[UIColor redColor]];<br />
[hello_label setBackgroundColor:[UIColor clearColor]];</code></p>
<p>Alright, there&#8217;s a lot here so lets break it down, starting with the first line.  This line basically allocates memory for <code>hello_label</code> and creates a CGRect for whatever we place inside of it.  Next, we set the UIFont properties for the label (for a list of available fonts, look at the end of the post) including the font itself (Arial) and the size (in px) of it (30).  After that, we position hello_label&#8217;s center point so that it won&#8217;t appear at the default (0,0), but instead at our own custom position (160,100) (this is 160 px from the left, and 100 px from the top; think cartesian plain, quadrant IV).  We then set the string that we want to display, in this case we are using the contents of <code>hello_text</code>, this is done by just using the <code>setText:</code> property.  After that, all we are doing is setting the color of the text and the background of the frame using UIColor again.  Notice something weird about the background color?  Instead of setting a visible color, we use a <code>clearColor</code>, which is essentially just transparency.  All that is left to do now is add the UILabel to our view and we can call it a day.</p>
<p><code>[self.view addSubview:hello_label];</code></p>
<p>This takes the object that we defined, and adds it to the superview.  Build &amp; Go.</p>
<div id="attachment_21" class="wp-caption alignnone" style="width: 169px"><img class="size-medium wp-image-21" title="Xcode Intro-1.4" src="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/Xcode-Intro-1.4-159x300.png" alt="Output" width="159" height="300" /><p class="wp-caption-text">Output</p></div>
<p>That is about it for now, Download the Hello World application used in this tutorial here: <a href="http://idevkit.com/iphonedev/wp-content/uploads/2009/09/iDK-HelloWorld.zip">HelloWorld</a></p>
<p>Regards,<br />
sj</p>
<p>Below is a console log of all the fonts and font families from <a title="Dave Mitchell's Blog" href="http://blog.lightvoid.net/2008/11/02/iphone-uifont-list/" target="_blank">Dave Mitchell</a></p>
<blockquote><p>Font Family: American Typewriter<br />
Font: AmericanTypewriter<br />
Font: AmericanTypewriter-Bold</p>
<p>Font Family: AppleGothic<br />
Font: AppleGothic</p>
<p>Font Family: Arial<br />
Font: ArialMT<br />
Font: Arial-BoldMT<br />
Font: Arial-BoldItalicMT<br />
Font: Arial-ItalicMT</p>
<p>Font Family: Arial Rounded MT Bold<br />
Font: ArialRoundedMTBold</p>
<p>Font Family: Arial Unicode MS<br />
Font: ArialUnicodeMS</p>
<p>Font Family: Courier<br />
Font: Courier<br />
Font: Courier-BoldOblique<br />
Font: Courier-Oblique<br />
Font: Courier-Bold</p>
<p>Font Family: Courier New<br />
Font: CourierNewPS-BoldMT<br />
Font: CourierNewPS-ItalicMT<br />
Font: CourierNewPS-BoldItalicMT<br />
Font: CourierNewPSMT</p>
<p>Font Family: DB LCD Temp<br />
Font: DBLCDTempBlack</p>
<p>Font Family: Georgia<br />
Font: Georgia-Bold<br />
Font: Georgia<br />
Font: Georgia-BoldItalic<br />
Font: Georgia-Italic</p>
<p>Font Family: Helvetica<br />
Font: Helvetica-Oblique<br />
Font: Helvetica-BoldOblique<br />
Font: Helvetica<br />
Font: Helvetica-Bold</p>
<p>Font Family: Helvetica Neue<br />
Font: HelveticaNeue<br />
Font: HelveticaNeue-Bold</p>
<p>Font Family: Hiragino Kaku Gothic **** W3<br />
Font: HiraKakuProN-W3</p>
<p>Font Family: Hiragino Kaku Gothic **** W6<br />
Font: HiraKakuProN-W6</p>
<p>Font Family: Marker Felt<br />
Font: MarkerFelt-Thin</p>
<p>Font Family: STHeiti J<br />
Font: STHeitiJ-Medium<br />
Font: STHeitiJ-Light</p>
<p>Font Family: STHeiti K<br />
Font: STHeitiK-Medium<br />
Font: STHeitiK-Light</p>
<p>Font Family: STHeiti SC<br />
Font: STHeitiSC-Medium<br />
Font: STHeitiSC-Light</p>
<p>Font Family: STHeiti TC<br />
Font: STHeitiTC-Light<br />
Font: STHeitiTC-Medium</p>
<p>Font Family: Times New Roman<br />
Font: TimesNewRomanPSMT<br />
Font: TimesNewRomanPS-BoldMT<br />
Font: TimesNewRomanPS-BoldItalicMT<br />
Font: TimesNewRomanPS-ItalicMT</p>
<p>Font Family: Trebuchet MS<br />
Font: TrebuchetMS-Italic<br />
Font: TrebuchetMS<br />
Font: Trebuchet-BoldItalic<br />
Font: TrebuchetMS-Bold</p>
<p>Font Family: Verdana<br />
Font: Verdana-Bold<br />
Font: Verdana-BoldItalic<br />
Font: Verdana<br />
Font: Verdana-Italic</p>
<p>Font Family: Zapfino<br />
Font: Zapfino</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://idevkit.com/iphonedev/2009/09/xcode-and-the-iphone-sdk/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
