How to Use Objective-C Variables, Constant & Types to Develop iPhone and iPad Apps

In the C programming like all other languages, variables, constants and types go hand in hand. In this second installment, I will show you how to declare and use variables and constants with their associated type. I know that the title must seem a little deceiving and you must be saying, “why is this guy talking about C programming in a tutorial on Objective-C variables, constants and types”. The answer is quite simple - C programming is the basis for Objective-C. In fact Objective-C is a superset of the C language. To really understand Objective-C, it is imperative that you know C first. It’s like the missing link as it were.

This tutorial is broken down into two parts: this part is on C variables, constants and types and second part is on Objective-C’s instance variables and constants in more depth.

Once we have a firm gasp on declaring variables and constants in C, I will show you how to declare variables and constants in Objective-C. I will also show you through some hands-on exercise how to declare and use C based variables and constants and Objective-C variables and constants.

Variables


Like any other programming language, you declare variables to hold temporary data that you will use in you program. As the name suggests, a variable’s value can mutate during a programs executing lifetime; variables and their values can short lived or have very long life-cycles. In Objective-C, variables are called instance variables. In C and all its derivatives (Objective-C, C++, C#, Java, etc.), you declare a variable by preceding the variable name by its intended data type, like so:



float variable_one;
int name;



You can also declare a variable using a pointer, like this:



char[] *astring;



In Objective-C, you could also use cocoa classes:



NSString word;

Variables are usually declared at the beginning of a function or a method in the case of Objective-C and are written in lowercase as define in the ANSI C standard. All variables in C must be declared before you can use them and they must be initialized with an assignment.


Assigning a value to variable in C follows this syntax: data type - variable name - equal sign - value of assignment - semi-colon to complete the statement. Or variable name - equal sign - value of assignment - semi-colon.

example:

float apples = 6.5;

float tomatoes;
tomatoes = 5;

Also you cannot use a reserved keyword as a variable name. Here is a list of them:

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • entry
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • 
long
  • 
register
  • return
  • short
  • signed
  • sizeof
  • static
  • struct
  • switch
  • typedef

  • void

  • volatile
  • union
  • unsigned
  • while

Additionally, you cannot use an underscore at the beginning of a variable name like:



int _varname = 0;



However you can use them two concatenate two words, like:



short mountain_bikes = 1;


Scope of a variable
Variables can be declared both inside a function or method in Objective-C, or externally like in a header file. External variables - external is not a keyword, rather it simply to express that the variable is outside of any function - can be use by any function or method. When talking about internal or external variables, we generally mean scope. An external variable is visible to all functions, methods, objects in the same source file or header file or to other classes (Objective-C), functions or methods (Objective-C) if the variable is in a header file and the header file has be included in the implementation file of the calling class using either the #include, C or #import in Objective-C.

Variables that are declared inside a function or method is only visible within that processing block. They can be considered as local or internal. Internal variables come into focus when function or method is used and go out of focus when the function or method is finished and the variable has been released from memory.

You cannot declare and use multiple variables with the same name in the same program. However you can use a variable multiple times and a variable’s value can change over time.

Constants

Constants are very similar to variables except that their values are set when they are initialized and they cannot be changed. You declare a constant in C using the static keyword:



static float money = 100.00;

or

extern float money = 100.00

or

extern char * const letter = ‘a’;

or

static const char letter = ‘a’;

or
static char const letter = ‘a’;


These different declarations has to do with scope and linkage. Using the keyword signifies that 1) the variable is permanent, it cannot be changed once initialized, 2) it has an internal scope. Alternatively, the extern keyword is also 1) static in scope meaning that it is value once set cannot be changed, and 2) its scope is public or visible everywhere.

You can also use the #define directive which give a meaningful name to a constant.

Types


Types or data type in programming is the kind of value the variable (or constant) will contain.

Here are a list of types in C:

short, int, long
These are whole numbers, 100, 5 or 1000, or even 1000000. They don’t have a decimal point.

In Objective-C, you can express a 64-bit long data type as long long.

float, double
These numbers have a decimal point. The float has a floating point precision and is stored as a mantissa and an exponent. Example 521.4 is equal to 5.214x102. A double has a double precision and uses more bits, thus memory memory than a float. These numbers can also be expressed as 36.5 or 36.5f.

char
A char is one character and the value is enclosed in single quotation marks like ‘a’. In C, you can define s string of characters as an array like: ‘acbftg’. Any word is a string of characters of type char. There is no string data types in C.

pointers
A pointer is a memory address. It is declared using an asterisk *. It is dereferenced by preceding the variable with an ampersand like &variablename. I will have a tutorial on pointers.

struct
A struct is a meta type since defines new data types. More on structs later.

In Objective-C, there are a few more data types:

id
The id data type is a special type or general purpose type that allows for the storage of reference to any object or any data type.

BOOL
BOOL is short for boolean. It is a true or false data type. There is not equivalent in C, however as in many other programs and in programming as a whole, true or false is usually expressed as 1 or 0. So you can use these values in C to emulate a boolean data type.

enum
An enum is a constant list of integer values.

Additionally a data type can be signed or unsigned. The default is signed which means in layman terms that a number can be negative or positive. A number that is unsigned is usually referred to a positive.

Examples - 1

Open Xcode and create a new CommandLine program under the Mac OS X Application category. Call it whatever you want. We are going to create some variables and constants and their associate types.

Create command line application of type C
Create command line application of type C

In the main.c file, declare a variable of type short and assign a value of 1. You are also setting up a print statement to output the evaluation of the expression to the console. The %d is a token placeholder and I will write about those in a later tutorial.

Declaration and assigning variables
Declaration and assigning variables

Next declare another variable, gallon of type int. Do not assign any value to it. On a second line, assign a value of pint * 4 and print out the results. This second expression assigned the value of the first variable, pint and performed an arithmetic operation before printing out the results. Again arithmetic operations in another tutorial.

Console output
Console output

Example - 2

In this example, using the same project, create a new file by choosing File -> New File from the menu. Under the C and C++ heading, select a header file template. On the next page, give it a name and create it in your project.

Header file
Header file

In the header variable, add three variables; the first one a static variable of type char and assign a value of ‘a’. The second variable add the const keyword of type char and assign a ‘@’ symbol. Finally for the third variable declared it as an extern const of type int. Assign a value for the appropriate type

This is the code from the header file:

static char letter = 'a';
static const char symbol = '@';
extern const int myNumber = 6;



Back in the source file, main.c, import or include the header using double quotes and not angle brackets. Now you will be able to use the variables and constants that you declare in the header file. Try it out:

//This assignment overrides the initial one in the header file
letter = 'p';
printf("A letter %d\n", letter);
printf("a symbol %d\n", symbol);
printf("a number %d\n", myNumber);


Import header with #include or #import
Import header with #include or #import

Example 3 - float and double

In the main.c file, declare two new variables, one with a float data type and the other with double data type. The variable with the float data type, append the letter ‘f’ at the end of the number to explicitly assign the value as a float. You can print these out as well.




//float and doubles
float floater = 34.5f;
double dbl = 34.5;

Example 4 - enums

In the next little sample code declare two enums as shown below. Xcode allows two enum formats. In the first example, the value is literal. In the second you assign a value to a variable.

///this would be a enum
enum {
low,
medium,
high
}somenumbers;

//or

enum objC_Style_Enum {
one = 1,
two = 2
};

//to use in an if statement
if (low) {
//do someyhing
}

//or in a switch statement

switch (somenumbers) {
case low:
//do something
break;

default:
break;
}

Enumerations
Enumerations

Example 5 - strut

A strut is a type that creates a new type. In the example below, the strut strutit contains two members of type float; interestrate and investmentperiod.



//this would a strut
struct strutit {
float interestrate;
float investmentperiod;
}investment;


To use this strut, declare a new variable of type float, returnValue and assign the interestrate * investmentperiod. Also assign a value to the two variables in the investment strut, like so:



investment.interestrate = 3.5;
investment.investmentperiod = 1000;

float returnValue = investment.interestrate * investment.investmentperiod;

printf("The amount I will earn with this investment is %f.2\n", returnValue);

Variable declarations of other types
Variable declarations of other types

Example 6 - pointers

In this last example, I am a quick look at how to use pointers.


//this is a pointer

int * anumber;


printf("print an address to a number %d\n", &anumber);


//print a number from a dereference pointer
int number = 6;
int *pointernumber = &number;

printf("Print this number %d\n", *pointernumber);

In Summary

The next tutorial will cover instance variables and constants in Objective-C. It will cover object ownership; referring to instance variables; the different categories of instance variable. We will also cover constants.

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working