`
cenphoenix
  • 浏览: 161559 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

How to Create a Class in Objective-C

阅读更多

Have 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:

 

#import <Foundation/Foundation.h>


@interface Address : NSObject {

	NSString *Street;
	NSString *City;
	NSString *State;
	NSString *Zip;
}

@property (nonatomic,retain)NSString *Street;
@property (nonatomic,retain)NSString *City;
@property (nonatomic,retain)NSString *State;
@property (nonatomic,retain)NSString *Zip;

-(NSString *)googleHttpLink;
-(void) openGoogleMapsAppWithThisAddress;

@end

 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.

 

@implementation Address
@synthesize Street,City,State,Zip;

-(void)dealloc
{
	[Street release];
	[City release];
	[State release];
	[Zip release];
	[super dealloc];
}

 

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.

//
//  GoogleTestAppDelegate.m
//  GoogleTest
//
//  Created by cenphoenix on 10/25/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "GoogleTestAppDelegate.h"
#import "GoogleTestViewController.h"
#import "Address.h"

@implementation GoogleTestAppDelegate

@synthesize window;
@synthesize viewController;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
	Address *addressObject=[[Address alloc] init];
	addressObject.Street=@"1600 Pennsylvania Ave NW";
	addressObject.City=@"Washington";
	addressObject.State=@"DC";
	addressObject.Zip=@"20500";
	[addressObject openGoogleMapsAppWithThisAddress];
	
	[addressObject release];
	
    // Override point for customization after app launch    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}


- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


@end
 

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:

-(NSString *)googleHttpLink;
-(void) openGoogleMapsAppWithThisAddress;
 

and this to the implementation file:

-(NSString *)googleHttpLink
{
	NSString *street_temp=[NSString stringWithString:self.Street];
	street_temp=[street_temp stringByReplacingOccurrencesOfString:@" " withString:@"+"];
	
	NSString *city_temp=[NSString stringWithString:self.City];
	city_temp=[city_temp stringByReplacingOccurrencesOfString:@" " withString:@"+"];
	
	NSString *state_temp=[NSString stringWithString:self.State];
	state_temp=[state_temp stringByReplacingOccurrencesOfString:@" " withString:@"+"];
	
	NSString *zip_temp=[NSString stringWithString:self.Zip];
	zip_temp=[zip_temp stringByReplacingOccurrencesOfString:@" " withString:@"+"];
	
	NSString *temp=[NSString stringWithFormat:@"http://maps.google.com/?q=%@+%@+%@+%@",
					street_temp,city_temp,state_temp,zip_temp];
	return temp;
	
}


-(void) openGoogleMapsAppWithThisAddress
{
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self googleHttpLink]]];
}
 

 

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.

 

 

 

  • 大小: 96.1 KB
分享到:
评论

相关推荐

    Learn Objective-C for Java Developers 2009 (Apress)

    It will show them how to take their existing language knowledge and design patterns and transfer that experience to Objective-C and the Cocoa runtime library. This is the express train to ...

    Objective-C for Absolute Beginners: iPhone and Mac Programming Made Easy

    - **Creating Cool Apps:** With a solid foundation in Objective-C and familiarity with Cocoa and Cocoa Touch, you'll be ready to create your own applications. The book provides practical examples and ...

    Objective-C 的模拟对象

    // create a mock for the user defaults id userDefaultsMock = OCMClassMock([NSUserDefaults class]); // set it up to return a specific value when stringForKey: is called OCMStub([userDefaultsMock ...

    IOS5 Programming Cookbook

    To create a new iOS project in Xcode, you need to choose a template (such as a single view application) and provide project details like the product name, organization name, and language (Objective-C)...

    Advanced Apple Debugging & Reverse Engineering v0.9.5

    Whether you’re using Swift, Objective-C, C++, C, or an entirely different language in your technology stack, you’ll need to learn how to create breakpoints. It’s easy to click on the side panel in ...

    How to Create hello world iphone application

    ```objective-c - (IBAction)hello:(id)sender { [showHello setText:@"Hello World! Hello Aragon! Hello WenQi!"]; } ``` 3. **建立控件连接**: - 在Interface Builder中,按住Control键,从视图控制器...

    Beginning Swift Programming.pdf

    Enter the Swift future of ...Learn how to use generics to create highly reusable code Learn the new access controls mechanism in Swift Get up to speed quickly to remain relevant and ahead of the curve.

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Apply a transformation function to all values in a dictionary. - **Key Concepts:** - Iterating over dictionary items. - Modifying values using a provided function. 34. **(Almost)...

    Learn Cocoa on the Mac Feb 2010.pdf

    The Objective-C class reference documentation alone would fill thousands of printed pages, not to mention all the other tutorials and guides included with Xcode. Where do you start? Which classes are...

    Packt.Swift.Functional.Programming.2nd.Edition.2017

    Meant for a reader who knows object-oriented programming, has some experience with Objective-C/Swift programming languages and wants to further enhance his skills with functional programming ...

    CS193P IOS APPLICATION DEVELOPMENT Assignment 1 Walkthrough.pdf

    The main objective of this assignment is to reproduce the demonstration given in class, which involves building a simple calculator application for the iPhone. This assignment aims to help students ...

    Myclassroom教学设计焦雨昕.docx

    In conclusion, this teaching design for Unit 1 "My Classroom" aims to engage students in an interactive and meaningful way. By integrating various teaching methods such as the Situational, Task-based,...

    SAS Marketing Automation Overview

    Overall Class Learning Objective In this course, you learn how SAS Marketing Automation can be used to create and execute tasks for outbound marketing campaigns. Learning Process The training that you...

Global site tag (gtag.js) - Google Analytics