Archive | Code Tips RSS feed for this section

How to Use UITextField in iPhone Programming

Here is the standard way of getting user input and then using the input in your app.

UITextField works with the delegation pattern in Objective-C. That is, you need to designate an object to act “on behalf” of the text field object. In this video I show you how to use the UITextField to ask a user for input and then post the results to a label.

NOTE: The code in the video would cause a memory leak because the label and text field where not released after being added to the subview collection (take a close look)… See the code box below for the complete non-leaky code.

Here is the code from the example:

Implement the UITextField Delegate

The first thing we needed to do was indicate that our view controller would be acting as a delegate for the UITextField. To do this you simply need to declare it in the interface file:

#import 
@interface TextField : UIViewController<UITextFieldDelegate> {
}
@end

Add the UILabel and UITextField Objects

This part is straightforward enough: you essentially create a label and a text field and add them both to the view controller’s subview collection. This is the typical pattern used to build up a view in code.

#import "TextField.h"
@implementation TextField
UILabel *label;
UITextField *textField;
- (void)viewDidLoad {
[super viewDidLoad];
//Create label
label = [[UILabel alloc] init];
label.frame = CGRectMake(10, 10, 300, 40);
label.textAlignment = UITextAlignmentCenter;
label.text = @"";
[self.view addSubview:label];
[label release];
// Initialization code
textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 50)];
textField.delegate = self;
textField.placeholder = @"<Enter Text>";
textField.textAlignment = UITextAlignmentCenter;
[self.view addSubview: textField];
[textField release];
}
- (void)dealloc {
[textField release];
[label release];
[super dealloc];
}
@end

I didn’t bother highlighting here because the entire block of code is needed to create the two objects.

Implement a Delegate Method

This is the part that is fuzzy for most new iPhone programmers so please bear with me. Your UITextField object called textField above was added to the subview collection of the view controller we are essentially writing our code in. This view controller is capable of being a delegate for any text field because we indicated as much in the interface file. Furthermore, our view controller will serve as a delegate to our UITextField object, textField, because we set textField’s delegate property to the view controller by using the “self” keyword.

So, what this all means is that now our view controller will act on behalf of textField. So, our view controller will intercept and respond to events such as user’s starting to edit. Generally, when using text fields we need to be able to respond when the user touches the “Return” key. We do this by implementing a delegate method called textFieldShouldReturn in whatever object is serving as the delegate for the text field. In this case, it is our view controller.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
label.text = textField.text;
[textField resignFirstResponder];
return YES;
}

This delegate method activates when the user touches the return button. It does two important things: assigned the label’s text property to the value that the user input and it dismisses the keyboard.

That is how to use a text field to get input. For new iPhone programmers the pattern of delegate seems odd, but it does add some flexibility since the alternative could have required us to create an entire new subclass of UITextField to respond to the user events we need. Regardless, delegation is something that you should spend some time wrapping your head around since it is used often in iPhone programming and Objective-C in general.

Learn How To Make Your Own iPhone, iPad iOS apps!

Buy Now

If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.

You Get the 5 Essential Things You Need to Make iPhone Apps

  • C Procedural Programming
  • Objective-C Object Oriented Programming
  • Cocoa-Touch Model-View-Controller Design Pattern
  • Architecture of Real World iPhone Apps
  • 12 Step App Development Formula

This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.

Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:

Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

Read full story Comments { 1 }

Here is How You Use the Segmented Control [UISegmentedControl]

A segmented control displays a list of options that a user can choose from. Each segment sort of looks like a button; the segments remains “pressed” even after the user lifts his or her finger.

You can detect when a different segment is selected and also what corresponding value in an array (that you supply) is referenced by the selected segment. Here is an example of what a UISegmentedControl looks like:

Picture-Of-A-Segmented-Control

Today I can going to show you how to use a segmented control in Objective-C code using the UISegmentedControl class. First thing is a video followed by the written instructions:

Here Are the Steps To Use UISegmentedControl

  • Create A View Based XCode Project
  • Add A UILabel To the Controller:
  • #import "UseSegmentedControlViewController.h"
    @implementation UseSegmentedControlViewController
    UILabel *label;
    - (void)viewDidLoad {
    [super viewDidLoad];
    //Create label
    label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 10, 300, 40);
    label.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:label];
    }
    - (void)dealloc {
    [label release];
    [super dealloc];
    }
    @end
  • Create An Array:
  • NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
    
  • Create An Instance of UISegmentedControl:
  • UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
    
  • Customize the Control By Setting It’s Properties:
  • segmentedControl.frame = CGRectMake(35, 200, 250, 50);
    segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
    segmentedControl.selectedSegmentIndex = 1;
    
  • Set A Target and Action (The Code That Will Execute When The User Selects A New Segment):
  • [segmentedControl addTarget:self
    action:@selector(pickOne:)
    forControlEvents:UIControlEventValueChanged];
    
  • Add the Segmented Control to the view:
  • [self.view addSubview:segmentedControl];
    [segmentedControl release];
    
  • Implement the Action:
  • - (void) pickOne:(id)sender{
    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    label.text = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
    }
    
  • Release the UILabel in dealloc:
  • - (void)dealloc {
    [label release];
    [super dealloc];
    }
    

    Here Is the Complete Code For the UIViewController:

    //  Segmented Control code originally from Code_Toolbox Bonus Item
    //    from the ebook @
    //      http://howtomakeaniphoneapp.com
    //
    #import "UseSegmentedControlViewController.h"
    @implementation UseSegmentedControlViewController
    UILabel *label;
    - (void)viewDidLoad {
    [super viewDidLoad];
    //Create label
    label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 10, 300, 40);
    label.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:label];
    //Create the segmented control
    NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentedControl.frame = CGRectMake(35, 200, 250, 50);
    segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
    segmentedControl.selectedSegmentIndex = 1;
    [segmentedControl addTarget:self
    action:@selector(pickOne:)
    forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentedControl];
    [segmentedControl release];
    }
    //Action method executes when user touches the button
    - (void) pickOne:(id)sender{
    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    label.text = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
    }
    - (void)dealloc {
    [label release];
    [super dealloc];
    }
    @end

    Be Sure To Check Out the Header Files In XCode To See All Your Options

    You can change the look and feel of the UISegmentedControl by altering the background color. You can use your own images and add/remove segments on the fly.

    What Could You Use UISegmented For In Your App?

    Let me know in the comments below. Be sure to link to your apps on iTunes if you have them up yet!

    Learn How To Make Your Own iPhone, iPad iOS apps!

    Buy Now

    If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.

    You Get the 5 Essential Things You Need to Make iPhone Apps

    • C Procedural Programming
    • Objective-C Object Oriented Programming
    • Cocoa-Touch Model-View-Controller Design Pattern
    • Architecture of Real World iPhone Apps
    • 12 Step App Development Formula

    This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.

    Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:

    Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

    Read full story Comments { 2 }

    How to Play a Short Sound in iPhone Code

    Today I am going to turn my iPhone into a Ray Gun by having it play a short laser sound. You probably have seen the many gun, laser and farting apps available on the Apple App Store. Most of these apps simply play a short sound along with some fancy graphics.

    Here is how you can play a short sound:


    Here is the a summary of the steps I took in the video:

    Create a View Based iPhone Application

    First, create a view based iPhone application in XCode and add a button to your view that will play the sound. If you need a refresher on how to use Interface Builder to hook up controls check out my article on adding a slider control.

    Add the Audio Toolbox framework

    Drag in the Audio Toolbox framework into your frameworks group in XCode. Here is a video on how to quickly add frameworks in XCode if you need it: Quick Tip: Adding Frameworks Painlessly in XCode. Remember that the framework will be all one word with the .framework extension, AudioToolbox.framework.

    Add a short wav file to your project

    I used the website Joe’s Original Wave Files for this demo and found a nice laser sound to use. You can also buy the rights to use sounds in apps that you want to sell from websites like iStockPhoto.

    Use Audio Services to play the sound

    To keep things simple I put all the code that you need to play the sound in an IBAction called “shoot”.

    -(IBAction) shoot{
    //Get the filename of the sound file:
    NSString *path = [NSString stringWithFormat:@"%@%@",
    [[NSBundle mainBundle] resourcePath],
    @"/jad0007a.wav"];
    //declare a system sound id
    SystemSoundID soundID;
    //Get a URL for the sound file
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    //Use audio sevices to create the sound
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
    //Use audio services to play the sound
    AudioServicesPlaySystemSound(soundID);
    }
    

    That is it – pretty simple way to add some cool effects to your app.

    Learn How To Make Your Own iPhone, iPad iOS apps!

    Buy Now

    If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.

    You Get the 5 Essential Things You Need to Make iPhone Apps

    • C Procedural Programming
    • Objective-C Object Oriented Programming
    • Cocoa-Touch Model-View-Controller Design Pattern
    • Architecture of Real World iPhone Apps
    • 12 Step App Development Formula

    This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.

    Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:

    Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

    Read full story Comments { 12 }

    How to Make Your iPhone App Send Email with Attachments

    mailbox.jpgWould you like your users to be able to send email with attachments from your app?
    In iPhone OS 3.0 you can easily send pictures and voice recordings from your app in an email. In fact, now your emails can be easily formated using HTML and once the user has finished the email control returns back to your app. Pretty nifty!

    Here is how you do it:



    Add the Framework
    Add the “MessageUI” framework to your projects “Frameworks” group folder in XCode
    NOTE: if you are having trouble locating the framework follow this path: Macintosh HD>Developer>Platforms>iPhoneOS.platform>developer>SDKs>
    iPhoneOS3.0.sdk>System>Library>Frameworks
    TIP: add a shortcut to the Frameworks folder to your Finder sidebar since you will need it often
    Choose a Delegate
    Choose one class to act as the MFMailComposeViewControllerDelegate
    Import Message Framework
    Import “MessageUI.h” and “MFMailComposeViewController.h” to the header file of the delegate
    Make your Delegate
    Indicate that your delegate class is the delegate by including this <MFMailComposeViewControllerDelegate> in the @interface declaration
    Implement the Delegate Method
    Implement the “didFinishWithResult” MFMailComposeViewControllerDelegate delegate method and make sure to return control to the program by sending the dismissModalViewControllerAnimated message.

    -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult (MFMailComposeResult)result error:(NSError*)error {
    [self dismissModalViewControllerAnimated:YES];
    }

    Start Composing the Email Use an instance of MFMailComposeViewController to start composing the email and adding the attachments. This controller gives control to the user so s/he can decide to send or cancel the message.

    -(IBAction)mailIt {MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"I have a pencil for you"];
    UIImage *roboPic = [UIImage imageNamed:@"RobotWithPencil.jpg"];
    NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
    [picker addAttachmentData:imageData mimeType:@"image/jpg" fileName:@"RobotWithPencil.jpg"];
    NSString *emailBody = @"This is a cool image of a robot I found.  Check it out!";
    [picker setMessageBody:emailBody isHTML:YES];
    [self presentModalViewController:picker animated:YES];
    [picker release];
    }

    Now if you test this out you should be able to send an email from your app.
    Here is how I did the whole thing on video:
    http://screencast.com/t/uz7OV6XW
    A Few Notes
    So, as you can see it is pretty simple to compose an email in iPhone OS 3.0. You can use HTML tags to format the email; just insert the tags into your NSString that you send with the setMessageBody message. Attachments simply use the addAttachmentData method.
    Note: this example assumes that you and your users are all up to date with iPhone OS 3.0. To see an example of how to check for this and accommodate your users who are not up to date go to the Apple Developer website and look over the source code for the project “MailComposer”.

    Learn How To Make Your Own iPhone, iPad iOS apps!

    Buy Now

    If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.

    You Get the 5 Essential Things You Need to Make iPhone Apps

    • C Procedural Programming
    • Objective-C Object Oriented Programming
    • Cocoa-Touch Model-View-Controller Design Pattern
    • Architecture of Real World iPhone Apps
    • 12 Step App Development Formula

    This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.

    Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:

    Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

    Read full story Comments { 12 }

    How to Use a View Controller Programatically

    iStock_000004484548XSmall.jpgView Controllers are responsible for managing the graphical elements (the View) that appear on the screen of the iPhone. The graphical elements that make up the view can be created in Interface Builder (IB) or in code.
    Some people prefer to use Interface Builder while others prefer to use code. As the statisticians in my last job used to say,

    “Some like to see the pictures and some like to read the book”.

    Using IB is like seeing the pictures – you see all the controls in front of you and you can lay them out visually. Writing code is like reading the book – you know precisely what is going on with the controls because you can see all the code that they are using.
    Pros, Cons & a Confession
    I should say right up front that I do not like Interface Builder. It never really made sense to me and I found it difficult to work with. That being said, many people do like IB because it comes with tools that help you lay out your controls in a pleasing way. You can experiment easily with your UI without constantly rebuilding your project to see the results of your code changes.
    At any rate, today I am going to show you how to load a view controller with a label in code. I am hoping to use this as an example for the next few posts that will demonstrate different user controls. In the future I am thinking about comparing and constrasting doing these tasks in IB and in code.
    Adding a View Controller & Label in Code
    Add a New UIViewController Subclass
    From your XCode project, select “File”, “New File…” and then “UIViewController Subclass”. This adds a new UIViewController subclass to your XCode project.
    Instantiate a New Object Using initWithNibName
    Go to your app delegate’s implementation file (this is the file prefixed with your project name with the words “AppDelegate.m” attached to the end. Type this code into the applicationDidFinishLaunching method to instantiate your view controller and add it’s view to your app window. Don’t forget to import your view controller’s interface file at the top of the file.

    #import "TipOfTheWeekAppDelegate.h"
    //import your view controller interface file below:
    #import "ViewController.h"
    //this will reference your project name
    @implementation TipOfTheWeekAppDelegate
    @synthesize window;
    ViewController *vc;
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
     vc = [[ViewController alloc]
    initWithNibName:nil bundle:nil];
    
    [window makeKeyAndVisible];
    }
    - (void)dealloc {
     [vc release];
    
    [window release];
    [super dealloc];
    }

    @end

    Add Your View Controller Object to the App Window

    #import "TipOfTheWeekAppDelegate.h"
    //import your view controller interface file below:
    #import "ViewController.h"
    //this will reference your project name
    @implementation TipOfTheWeekAppDelegate
    @synthesize window;
    ViewController *vc;
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    vc = [[ViewController alloc]
    initWithNibName:nil bundle:nil];
     [window addSubview:vc.view];
    
    [window makeKeyAndVisible];
    }
    - (void)dealloc {
    [vc release];
    [window release];
    [super dealloc];
    }

    @end

    Add UI Elements to the View in the View Controller Objects’ loadView Method
    To do this step go to your view controller’s implementation file and find the loadView method. Simply add the code here that you need to create your user controls that will appear on the screen. For example, I will add a button to my view controller:

    #import "ViewController.h"
    @implementation ViewController
    UILabel *label;
    - (void)loadView{
    [super loadView];
     CGRect frame = CGRectMake(10, 10, 300, 300);
    label = [[UILabel alloc] initWithFrame:frame];
    label.textAlignment = UITextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Verdana" size:36];
    label.text = @"10";
    [self.view addSubview:label];
    }
    - (void)dealloc {
     [label release];
    [super dealloc];
    }

    @end

    So, that is it. It really only takes three steps to create a view controller and then load its view into your app. In the next few posts I am going to build on this example using different user controls.
    My Question to YOU:
    Do you prefer to use visual tools like Interface Builder or who you rather use code exclusively? Why or why not?

    Learn How To Make Your Own iPhone and iPad iOS apps!

    Buy Now
    If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.
    You Get the 5 Essential Things You Need to Make iPhone Apps

    • C Procedural Programming
    • Objective-C Object Oriented Programming
    • Cocoa-Touch Model-View-Controller Design Pattern
    • Architecture of Real World iPhone Apps
    • 12 Step App Development Formula

    This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.
    Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:
    Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

    Read full story Comments { 9 }

    For and ForEach Loops in Objective-C

    iStock_000008790379XSmall.jpgLoops are the gears of programming: they make your code take action.
    The two loops I use most often is the for loop (to do a predefined number of steps) and what is usually called a foreach loop (to move though a list of objects).
    //This loop simply repeats an action
    //a set amount of times:
    for (int i=0; i<=3; i++)
    NSLog([NSString stringWithFormat:@"i=%i", i]);

    //Create an array of strings for the next example:
    NSMutableArray *bunchOfThings = [[NSMutableArray alloc] init];
    [bunchOfThings addObject:@"Zero"];
    [bunchOfThings addObject:@"One"];
    [bunchOfThings addObject:@"Two"];
    [bunchOfThings addObject:@"Three"];
    //This is sometimes called a "for each" loop
    //Using this list will repeat actions for each
    //object in a list.
    //Hint: you can use this for any type of list of
    //objects so if you have list of custom defined
    //objects this is an easy way to work with them all
    //at one time.
    for(NSString *s in bunchOfThings)
    NSLog([NSString stringWithFormat:@"s=%@", s]);
    

     

    //The array must be released since it was alloc/init earlier.
    [bunchOfThings release];
    Learn How To Make Your Own iPhone and iPad iOS apps!

    Buy Now
    If you are completely new to iPhone programming and want to start to developing iPhone apps this ebook will give you everything you need to get started today.
    You Get the 5 Essential Things You Need to Make iPhone Apps

    • C Procedural Programming
    • Objective-C Object Oriented Programming
    • Cocoa-Touch Model-View-Controller Design Pattern
    • Architecture of Real World iPhone Apps
    • 12 Step App Development Formula

    This ebook is much different than the other books out there: it really is a *system* that includes ONLY what you need to know to make iPhone applications. Not only that, but you will get some real insight on how to make a product and how to set up your code in the best way the first time.
    Plus, you will get plenty of bonuses including exclusive source code projects. For more information, head on over to the website for the ebook:
    Head over to How To Make An iPhone App eBook Website website to find out how to get Matt’s eBook and the bonus source code.

    Read full story Comments { 1 }

    How to Create a Class in Objective-C

    ChalkboardObject.tiffHave you been wondering how to create a class and use it as an object in Objective-C?
    Anyone who is used to object-oriented programming will recognize the pattern demonstrated here. You will learn how to: use properties, allocate and de-allocate objects in memory, use a methods and you will see how to launch the Google Maps app on the iPhone with your address information.
    Please note that their are many different ways and some subtleties to implementing a class in Objective-C that will not be discussed here. My goal is to show you the simplest way to get up to speed as soon as possible.
    Address Class Introduction
    The “Address” class simply stores address information such as street, city and zip code. Address will also return the correctly formated link that Google Maps needs to map the address location. Finally, Address will take the Google link, launch the Google Maps app and drop a pin at the location of the address.
    NSObject Subclass
    From XCode, select “File” and then “New File…”. You will see a dialog box come that looks like something like this:

    Choose NSObject subclass and call it “Address”. XCode will create two files for you: Address.h and Address.m. Classes have two files associated with them: the header file (“h” file extension) and the implementation file (“m” file extension).
    The best way to think of the header file is that this is the place were you will define what your class does (but you do not implement anything here). Most of the coding will be done in the “m” file.
    Add the Street, City and Zip Properties
    In object-oriented programming, classes have properties and methods. Properties describe attributes of the thing represented by the class while methods are the class behaviors. The properties of the Address class are: Street, City, State and Zip – attributes that describe an address.
    In Objective-C you must add code in a few places in both the header and implementation files in order to use properties.
    In the header file you add code in two places:

    In the implementation file you need to “synthesize” the properties using @synthesize. It is also important to add code to release the memory associated with the properties in the class dealloc method.

    After you put your code in these four places your properties are ready to be used.

    Detour: Using the Address Class Properties in Your Code

    Now that you have properties defined in your address class you can use the class to create an object that stores address information. To keep things simple I will add the code right in the app delegate in the applicationDidFinishLaunching method. This is generally the first place you will add code to a new iPhone app.

    NOTE: this file is the implementation file for you app delegate. It is usually named something like: “<yourProject>AppDelegate.m”.

    First thing I had to do was add a reference to the Address header file I created. This goes at the very top and looks like this:

    #import “Address.h”

    Now, I simply need to add code to use an address object. The basic pattern is this: allocate memory, create object, use object and de-allocate memory. I will create an Address object, assign address information to it, write out that information to the log and finally I will de-allocate the memory associated with the Address object.

    So, that is that – now you can create and use a class in Objective-C. Before we end I want to make this class a little bit more useful by adding a method to create the hyperlink that Google needs to find the address on the map. Then I want give my address objects the ability to launch the Google Map app on the iPhone with the address information contained in the object.
    Launch Google Maps from the Address Class
    In order to Google Map functionality to the Address class I need to do two things: create a function that will return the address information in string formatted to work with Google Maps and I need to create a method that will take that string and open the Google Maps app.
    To create the function I add this to the header file:

    and this to the implementation file:

    To add the method that opens up the Google Maps app I put this into the header file:

    and this into the implementation file:

    Conclusion + Where to Get the Files
    So, that is it – you now should be able to create your own Objective-C classes to use in your iPhone projects and you have some clues about how to use the Google Maps app. I hope you enjoyed this tutorial. If you have any comments please put them in the form below.
    Here is the link to the source code used for this tutorial:
    Complete Xcode Project


    Read full story Comments { 5 }

    Make Your Life Easier With Reusable Code

    If you have spent any amount of time learning or working with the iPhone SDK then you are probably getting frustrated with the very wordy (and difficult to remember) nature of the Cocoa framework.  Things that are trivial in environments like .NET or Java can seem awkward and clumsy in Cocoa.
    As an example of this wordiness, here is what I do to create a button in code:

     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectZero;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    button.frame = CGRectMake(10, 10, 100, 50);
    [button setTitle:@"Button" forState:UIControlStateNormal];

    And here is what I routinely do to use a simple alert box (one line of code in .NET):

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Help Message"
    message:message
    delegate:self
    cancelButtonTitle:@"OK"
    otherButtonTitles: nil];
    [alert show];
    [alert release];

    To be fair, every programming language has issues like this to some extent and the purpose of this post is not to bash Cocoa.  The purpose of this post is to suggest a way to make your life easier by learning how to reuse your code.
    WARNING: There is a 50% chance that what I am about to suggest will deeply offend you!
    There are a few different ways to make your code reusable – in object-oriented programming whole books have been written about this.  What I am about to tell may offend both object-oriented purists as well as people who truly love the way Cocoa does things.
    My suggestion is to simply pay attention to the code that you are writing over and over again;  then put this code into static functions in a class that you can simply call from any other classes.  Programming veterans will be familiar with this approach (and might as well skip to the code examples at this point).
    So, if you put all that wordy code into a static function you can use that code in the future with only one line required to get the same behavior.  This makes your code more readable and will decrease your time coding because you are not re-doing the same thing over and over again.
    WHY WOULD SOMETHING SO COOL OFFEND PEOPLE?
    This approach is basically creating global functions and sort of steps on the toes of good object-oriented design that insists that objects created from a class that have all the information and behavior required to get by in your program.  Intermixing global functions doesn’t quite fit into this and could lead to the problem of “spaghetti code” if you are not careful or if you are excessive in this approach.
    Other people simply believe that the Cocoa way is the best way and that essentially creating your own framework on top of Cocoa some form of denial system.   Like most system design choices there are +/- and you will have to keep your thinking cap on.
    HERE IS WHAT I DO
    Personally, I use static functions to help me work with using the log since I hate using the NSString stringWithFormat nonsense.  I also use it for alerts and buttons.  In general, I try to keep the global static functions to very general things and keep anything else in the class where it belongs.  For example, all database access functions I put into a SQLite object that just accesses data.
    NSLOG EXAMPLE
    I use NSLog a lot while debugging code and even though it only requires one line of code I find it awkward to use.  So, I have created three static functions to automate this for me:

    +(void) logThis:(NSString *) message;
    +(void) logThis:(NSString *) message andThisFloat:(float) number;
    +(void) logThis:(NSString *) message andThisObject:(id) object;

    This makes it easy to shoot out a message to the log – either by itself, with number value (very common need) or the string value of any object.
    Here I will show you the steps required to create these static functions so that you can do for yourself in the future.
    First, open up your favorite XCode project and add a NSObject subclass file.  You will have two files (one with a h file extension and one with a m file extension).  You will need to edit both. 
    Open the header file (with the h!) and add this code:

    #import
    @interface ASFunctions : NSObject {
    }
    +(void) logThis:(NSString *) message;
    +(void) logThis:(NSString *) message andThisFloat:(float) number;
    +(void) logThis:(NSString *) message andThisObject:(id) object;
    @end

    Now, add this code to the implementation file (m):

    +(void) logThis:(NSString *) message{
    NSLog(message);
    }
    +(void) logThis:(NSString *) message andThisFloat:(float) number{
    NSLog([NSString stringWithFormat:@"%@ = %f", message, number]);
    }
    +(void) logThis:(NSString *) message andThisObject:(id) object{
    NSLog([NSString stringWithFormat:@"%@ = %@", message, object]);
    }

    Put this after the @implementation but before the @end.  Ok, almost done.  In order to use this from another part of the program you must add some code to the file you are working with.  For instance, I am going to add these functions to my app delegate for simplicity.  Add the reference to the header file to the top:

    #import "ASFunctions.h"

    Now all you need to do is simply call the functions as you need them. Since they are static you do not need to worry about allocating the object. Here is how to use the simplest log function I wrote:

     [ASFunctions logThis:@"Writin' to da log!"];

    Using the other functions is similar:

     [ASFunctions logThis:@"Writin' to da log!" andThisFloat:4];

    Well, that is it. These examples are almost too simple for this approach but I hope they give you some ideas about the code you would like to put into static functions.
    Want some input about the future direction of this blog? Please fill out our survey!
    What do YOU think?  What functions make sense to be put into global static functions?  What don’t?  Should everything be object-oriented or what?
    Comment below!

    Read full story Comments { 8 }

    Here is How you Use a Class in Objective-C

    In this post I am going to demonstrate how to create a class and use it as an object in Objective-C.  Anyone who is used to object-oriented programming will recognize the pattern demonstrated here.  You will learn how to: use properties, allocate and de-allocate objects in memory, use a methods and you will see how to launch the Google Maps app on the iPhone with your address information.
    Please note that their are many different ways and some subtleties to implementing a class in Objective-C that will not be discussed here.  My goal is to show you the simplest way to get up to speed as soon as possible.
    Address Class Introduction
    The “Address” class simply stores address information such as street, city and zip code.  Address will also return the correctly formated link that Google Maps needs to map the address location.  Finally, Address will take the Google link, launch the Google Maps app and drop a pin at the location of the address.
    First Things First
    From XCode, select “File” and then “New File…”.  You will see a dialog box come that looks like something like this:

    Choose NSObject subclass and call it “Address”.  XCode will create two files for you: Address.h and Address.m.  Classes have two files associated with them: the header file (“h” file extension) and the implementation file (“m” file extension).
    The best way to think of the header file is that this is the place were you will define what your class does (but you do not implement anything here).  Most of the coding will be done in the “m” file.
    Add the Street, City and Zip Properties
    In object-oriented programming, classes have properties and methods.  Properties describe attributes of the thing represented by the class while methods are the class behaviors.  The properties of the Address class are: Street, City, State and Zip – attributes that describe an address.
    In Objective-C you must add code in a few places in both the header and implementation files in order to use properties.
    In the header file you add code in two places:

    In the implementation file you need to “synthesize” the properties using @synthesize.  It is also important to add code to release the memory associated with the properties in the class dealloc method.

    After you put your code in these four places your properties are ready to be used.

    Detour: Using the Address Class Properties in Your Code

    Now that you have properties defined in your address class you can use the class to create an object that stores address information.  To keep things simple I will add the code right in the app delegate in the applicationDidFinishLaunching method.  This is generally the first place you will add code to a new iPhone app.

    NOTE: this file is the implementation file for you app delegate.  It is usually named something like: “<yourProject>AppDelegate.m”.

    First thing I had to do was add a reference to the Address header file I created.  This goes at the very top and looks like this:

    #import “Address.h”

    Now, I simply need to add code to use an address object.  The basic pattern is this: allocate memory, create object, use object and de-allocate memory.  I will create an Address object, assign address information to it, write out that information to the log and finally I will de-allocate the memory associated with the Address object.

    So, that is that – now you can create and use a class in Objective-C.  Before we end I want to make this class a little bit more useful by adding a method to create the hyperlink that Google needs to find the address on the map.  Then I want give my address objects the ability to launch the Google Map app on the iPhone with the address information contained in the object.
    Launch Google Maps from the Address Class
    In order to Google Map functionality to the Address class I need to do two things: create a function that will return the address information in string formatted to work with Google Maps and I need to create a method that will take that string and open the Google Maps app.
    To create the function I add this to the header file:

    and this to the implementation file:

    To add the method that opens up the Google Maps app I put this into the header file:

    and this into the implementation file:

    Conclusion + Where to Get the Files
    So, that is it – you now should be able to create your own Objective-C classes to use in your iPhone projects and you have some clues about how to use the Google Maps app.  I hope you enjoyed this tutorial.  If you have any comments please put them in the form below.

    Read full story Comments { 7 }
    Affiliate Policy Disclosure

    Switch to our mobile site