Tag Archives: xcode

Objective-C creating objects, methods and variables

In this tutorial we will be creating a console application to try every part of our code out. Please make sure that the console is not set to its default language, which is C and is instead set to foundation.

The first thing we need to do is create a no project with Xcode. I will be naming mine “test” but you really don’t need to follow along with that much detail since it is not needed at this stage with the level of coding we will be doing.

The next thing we will need to do is open up our “test.m” file through Xcode. This file contains the default main method but we are going to be creating objects and variables.

1
2
3
4
5
6
7
8
9
10
#import <Foundation/Foundation.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

Now you are going to need to create an interface and an implementation of the class made in the interface. Luckily for us Xcode has an auto complete feature built in that look something like this.

Until we start modifying the information in the interface and implementation you can just leave it with its default values that are given when it auto completes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#import <Foundation/Foundation.h>
 
@interface <#class#> : <#superclass#>
{
	<#ivars#>
}
 
<#methods#>
 
@end
 
@implementation <#class#>
 
<#methods#>
 
@end
 
 
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

The next thing we will be doing is creating the actual object from our interface. This requires us to create an object name, which in this case will be a “Person”, and it also requires a super class, which we will send to “NSObject.”

1
2
@interface Person : NSObject
{

Note: It is standard and common practice to associate objects as follows: “PersonObjectSomething.” You will notice that when naming all of the words are capitalized. This is common practice when naming classes. When naming methods it is standard to leave that first letter as a lower case like so “thisTestMethod.”

The next things that are required are instance variables. These are variables/information that is associated with the object. For example if we created an object that was a cup then we would have instance variables for weight, liquid capacity, circumference of base, etc.

For our person object we will be creating the instance variables for age and height. Normally I would like to do a name but I will be leaving the string library for another tutorial.

When declaring instance variables, or any variables, you will need to create the data type first then give the variable a name. A simple example of this would be an integer data type named x as you commonly see in math. You can also assign the variable a value when it is first declared.

1
2
int x;
int y = 32;

Once we have declared our instance variables for person you should have something that looks like this.

1
2
3
4
5
6
7
8
#import <Foundation/Foundation.h>
 
@interface Person : NSObject
{
	int height; // in CM
	int age;
}
@end

Now that we have created our Person interface’ variables we will need to create methods. If you have never worked with methods you may know them by another name, which is a function. If you still haven’t worked with them then you should know that a method is essentially a small sub program running in a larger one. Methods naturally return a value as well however, you can change the method type to void and not have to worry about returning a value.

There are two kinds of basic methods used in programming languages. The first one is called an accessor method and the second one is called a mutator method. The accessor method simply accesses a variable from the object it is derived from and returns said variable. And the mutator changes the value of the variable in some way. For this program we will be using these two types along with another void type that will print information on the screen.

In order to create a method, we must first link to it in the interface section of the code so our object can use it with the variables it contains. For this program we will need to set the height and age, access the height and age, and print the information on the screen. Add this section of code to your interface.

1
2
3
4
5
6
7
-(void)setHeight: (int) x;
-(void)setAge: (int) x;
 
-(int)getHeight;
-(int)getAge;
 
-(void)printInfo;

You should now have an interface that looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import <Foundation/Foundation.h>
 
@interface Person : NSObject
{
	int height; // in CM
	int age;
}
-(void)setHeight: (int) x;
-(void)setAge: (int) x;
 
-(int)getHeight;
-(int)getAge;
 
-(void)printInfo;
@end

The next thing we will need to do is create the body of our object. We can do this by filling out the implementation section of our code. As you can see in your Xcode’ code view we have a place for the class to be written and a place for the methods. We are going to change the class to “Person” and start writing in our accessor and mutator methods. When done we will have the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@implementation Person
 
-(void)setHeight: (int) x{
	height = x;
}
-(void)setAge: (int) x{
	age = x;
}
 
-(int)getHeight{
	return height;
}
-(int)getAge{
	return age;
}
-(void)printInfo{
	NSLog(@"height: %i age: %i",height, age);
}
@end

Now that we have created our methods and instance variables we will go ahead and create this object and put it into memory. The following code is what we currently have for a main method.

1
2
3
4
5
6
7
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

When creating objects there are two main terms you will need to familiarize yourself with. The first term is “init” Which of course stands for initialize. This is when you tell the machine that you are ready to use the object. The next term you should be familiar with is “alloc,” it is short for allocate. This is the process of freeing up memory in your ram for the storage of the object.

The code to initialize and allocate an object is written as follows.

1
2
3
Person *p1;
p1 = [Person alloc];
p1 = [p1 init];

In this process we first named the object p1 and assigned it enough space to hold the object “Person” in memory. The next line of code simply initializes the object so it is ready for our use.

When you are done using your object and you would like to delete it you must include an object release.

1
[p1 release];

In between creating the object in memory and removing it from memory we are going to add some code to set the variables, access the variables and display what the object holds on screen.

In order to display an object’s methods you will need to follow the form of writing the code as follows.

1
[p1 setAge:18];

You can see that the object is placed within square brackets and the first statement is the object name itself. The second statement accepts the method that you would like to call on then a colon and some parameters if you made a method that accepts arguments.

When using a method that returns a value it is possible to load the data type returned into another variable as long as it is of the same data type. We use an example of this with the following lines. You can also use a variable as an argument when setting an objects variable.

1
2
int g = [p1 getHeight];
[p1 setAge: g];

The entire program looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#import <Foundation/Foundation.h>
 
@interface Person : NSObject
{
	int height; // in CM
	int age;
}
-(void)setHeight: (int) x;
-(void)setAge: (int) x;
 
-(int)getHeight;
-(int)getAge;
 
-(void)printInfo;
@end
 
@implementation Person
 
-(void)setHeight: (int) x{
	height = x;
}
-(void)setAge: (int) x{
	age = x;
}
 
-(int)getHeight{
	return height;
}
-(int)getAge{
	return age;
}
-(void)printInfo{
	NSLog(@"height: %i age: %i",height, age);
}
@end
 
 
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	Person *p1;
 
	p1 = [Person alloc];
	p1 = [p1 init];
 
	[p1 setAge:18];
	[p1 setHeight:188];
	[p1 printInfo];
	int g = [p1 getHeight];
	[p1 setAge: g];
	[p1 printInfo];
 
	[p1 release];
    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

If you have any questions or concerns please feel free to comment below.

Objective-C garbage collecting

Garbage collecting is the process of freeing up system memory automatically so you, the programmer, don’t have to manually dump the memory from file. It can be turned on and is a great asset when programming with Objective-C.

Advantages of the garbage collector

The garbage collector, also known as “GC,” can actually increase the speed of programs as opposed to manually freeing up memory. This is because the garbage collector can take advantage of idle processors on your chip running in the background and not affecting your programs speed.

Requirements

Garbage Collector is only available on operating systems released after Snow Leopard 1.5, it is also not available when programming for the Ipod Touch or IPhone.

Enabling the Garbage Collector

In order to enable Garbage Collector you will need to open a new Xcode application if you have not done so already. Go to the top of the screen where you will see the menu item “Project,” now go down to “edit project settings.”

Once the window pops up you are going to need to click the build tab at the top then scroll down the list until you reach a heading on the left side entitled “GCC 4.2 – Code Generation” on Snow Leopard or “GCC 4.0 Code Generation.” Go down the list in this section to where it says “Objective-C Garbage Collection.” To the right of that setting it should be defaulted at “Unsupported” change this to “[-fobjc-gc]”

Now you have successfully enabled garbage collecting. This should be used with the new Macs since they have multiple cores. If you would like to manage memory manually you can go ahead and skip this article.

Introduction to Objective –C

In this tutorial I will be going through how to get and install Xcode, Create a new project, and run that project through the console. This is not an application tutorial it is purely objective-c.

The first thing that I will be showing you in this tutorial is where to get Xcode. First thing you should know is that Xcode does come on all new copies of OS X. If you do not have it already installed or you would like the new version, which I strongly recommend, that comes with the IPhone SDK. You can download it from the Apple website.

Note: This is the Iphone SDK. It is a rather large file but it will come with the latest version of Xcode.

Now we are going to start this tutorial by creating a new project. The project type that we will be creating is a simple hello world from the console. To do this you will need to start up Xcode, click new project. When the new project window appears, you should have a screen that looks like this.

Make sure that you have selected applications > console. This is important for what we will be doing. Also note that the language is set to C. We do not want this, instead we would like to use Objective C. Click down on the menu and select “Foundation.”

Now you should be ready to continue on with the introduction. Name the project “codewithdesigntest” and create the new project.

A window will appear now and this is where you will be working with code. There is one window that is not open that we will need open. This window is the console; it allows us to see what is being displayed as an output. In order to open it press (Command + Shift + R) or you can find run > console on the menu bar at the top of the screen.

The file extension for objective C is nice and simply “.m” which is the equivalent of .cpp, .java etc. In the top section of the screen you can see there are a bunch of files natively given to the programs build. We are going to open up the “’codewithdesigntest.m” by single clicking it. It should open in the bottom section of the screen.

1
2
3
4
5
6
7
8
9
10
11
#import 
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
 
}

Because the code is already setup and ready to run your hello world in the console, the only thing that is required is for you to run the code. At the top of your screen press the button build and run. Now make sure you can see the console on the screen, this will display your output.

If at the bottom it said build successful and closed normally then you are ready to continue on to learning Objective C.