Objective-C Course | How-To Use Objective-C Instance Variables

Object instance variable

IOS 5 and Mac apps like any other computer app uses variables to hold their data during the execution of the app. In Objective-C, in addition to variables used in C and their simple types, instances variables as they are own in Objective-C are often used as pointers to other objects and describes the relationship between the two. There three categories of instance variables:

Object-type attributes
This type of variable provides a pointer to a cocoa object like NSNumber, or NSString and NSInteger. In other words, if you store data in an variable of type NSString, you would have an instance variable pointing to an instance of NSString:

Object - Type Attribute Instance Variable
Object - Type Attribute Instance Variable

To-one relationships
The next type of instance variable would involve having one instance variable defined for an object pointing to instance of another object. Using our example for above, an instance variable of the Car class would point to an instance of the Vehicule class’s type variable:

To-one instance variable
To-one instance variable

To-many relationships
The last category of instance variables is for collection classes like arrays: NSArray and NSMutableArray.

To-many relationship instance variable
To-many relationship instance variable

Referring to instance variables

An instance method, or an instance of the class’s method has all instances variables within scope. Meaning they can refer to the instance variables by name. You don’t need to pass variable as a parameter:

Referring to instance variables
Referring to instance variables

Otherwise if an object is statically typed and that object is not the receiver, the instance variable needs to be explicit declared to the compiler. To refer to an instance variable that is statically typed, the structure variable pointer (->) must be used:

Referring to an instance variable from another object
Referring to an instance variable from another object

The receiver's instance variable

Any method has automatic access to the receiving object’s instance variables. However for variables stored in other object, you need to explicitly request for information from that variable otherwise the compiler will complain:

The receivers instance variable
The receivers instance variable

Scope

In Objective-C, scope can be defined using a compiler directive to provide flexibility and visibility as Objective-C classes hide their data by limiting the visibility of instance variables. The directives are:

@private
Instance variable is only visible within the class.

@protected
Instance variables are only visible within the class or any other class that inherits from it. All instance variables are @protected by default if no directive is used.

@public
The instance variable is accessible everywhere.

@package
The instance variable has a @public scope in the executable but @private outside the image executable. This is equivalent to the private_extern scope declaration in C.

Global Variables

Global variables are static variables. Static variables can be created with the #define directive, however Objective-C recommends the use of global variables instead. Global variables are defined in the header file of the parent object class using the extern directive:

Declaring global instance variable
Declaring global instance variable

A cool use of #define is being able to use it a a function. In the example below, whenever the preprocessor reads MyGlobalVariable, it will be replaced with 50.

Using #define
Using #define

Object ownership in Automatic Resource Counter (ARC)

The ARC maintains the object ownerships in a running program and releases them when they are no longer needed. It is still good practice to set an object to nil when it is no longer needed, but if you enable ARC when you create a project, you won’t need to release the resource.

Enabling ARC in a project in Xcode
Enabling ARC in a project in Xcode

Examples

The following examples can help you better understand the different concepts introduced in this tutorial. The first example demonstrates an Object-type attribute instance variable:

Create a Single View IOS app in Xcode. You can name it whatever you want. However make sure that ARC is enabled on the Project Name page. Once created, create a new NSObject object and save it as ObjectVariable.

Open the header file and enter the code as shown in the following screenshot.

Create the ObjectVariable Class
Create the ObjectVariable Class
Object type declaration in the header
Object type declaration in the header
Object type implementation
Object type implementation

When you declare an instance variable in the ObjectVariable that points to the NSString object, you are creating an instance variable belonging to the object-type attribute category.

The next category of instance variables is the To-one relationships.

In the same project as before, create a new NSObject by creating a new file and selecting the Objective-C class template. Name the NSObject object ToOneObject. In the header file add an instance variable, numbers, that points to the NSNumber class. Create a property using @property. In the implementation file create the accessor method.

You create an accessor using the @synthezise directive and the name of the instance variable that you defined in the header file, followed by the equal sign and the name of the instance variable preceded by an underscore. I will cover methods later:

The ToOne Header Code
The ToOne Header Code
ToOne Implementation
ToOne Implementation

Back in the ObjectVariable header file, define a method, myMethod, with a void return type and implement it in the implementation file. Next add an import directive to include the ToOneObj.h file. In the body of the method declare an instance variable, leChiffre, of type numbers.

So your instance variable, leChiffre, points to numbers which points to NSNumber. This is a To-one relationship.

Declare the numbers instance variable
Declare the numbers instance variable
Implement the numbers instance variable
Implement the numbers instance variable
Declare the myMethod
Declare the myMethod
Implement the numbers instance variable in the myMethod method
Implement the numbers instance variable in the myMethod method

Finally lets create a to-many relationship instance variable. To kick things off, declare an instance variable that points to NSMutableArray, set its property directive and create the accessor in the implementation method.

While still in the ToOneObj header file, add a method, addSomeVars, with a NSString parameter. In the implementation file, implement the method by initializing the manyVars NSMutableArray instance variable and call the addObject method of NSMutableArray to add a value, s, that is passed in through the addSomeVars parameter:

Declare NSMutableArray variable
Declare NSMutableArray variable
Implement NSMutableArray
Implement NSMutableArray

To make use the new functionality, open the ObjectVariable headre file add a new method, tooManyVars with a void return type. Finally implement it by creating a ToOneObj instance variable lotsOfVars that points to ToOneObj. After initializing it, call the addSomeVars method and add a value to the NSMutableArray.

Implement ToMany in ObjectVariable
Implement ToMany in ObjectVariable
Complete myMethod
Complete myMethod

Nice eh?
Ok to wrap things up, in the ObjectVariable header file, define a global variable and a constant using the #define preprocessor directive. See image above.

In the myMethod from before, add a value to the vars static variable and declare a new instance variable digits of C type int and assign the defineAConst value. To complete the example, create yet another int variable, sumOfDigits and assign an expression of 2 * digits. When the app runs the method will get called, the defineAConst constant will be replaced by 10 * 5 and the sumOfDigits will contain the result of 2 * 50 or 100. See image above.

In Summary

Try some more exercises on your own and experiment with the different instance variable categories. Objective-C has some very elegant techniques for using variables in addition to all the types and variables in C.

ToOneObject.h

//
//  ToOneObject.h
//  LearnObjCPart2
//
//  Created by Kevin Languedoc on 1/17/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ToOneObject : NSObject
{
    NSNumber *numbers;
    NSMutableArray *manyVars;
}

@property(strong, nonatomic) NSNumber *numbers;
@property(strong, nonatomic) NSMutableArray *manyVars;

-(void)addSomeVars:(NSString *)s;
@end

ToOneObject.m

//
//  ToOneObject.m
//  LearnObjCPart2
//
//  Created by Kevin Languedoc on 1/17/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import "ToOneObject.h"

@implementation ToOneObject
@synthesize numbers = _numbers;
@synthesize manyVars;

-(void)addSomeVars:(NSString *)s{
    manyVars = [[NSMutableArray alloc]init];
    [manyVars addObject:s];
}
@end

ObjectVariable.h

//
//  ObjectVariable.h
//  LearnObjCPart2
//
//  Created by Kevin Languedoc on 1/17/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import <Foundation/Foundation.h>

#define defineAConst 10 * 5
extern NSString const *vars;

@interface ObjectVariable : NSObject{
    NSString * stringVar;
}

@property (strong, nonatomic) NSString * stringVar;


//method
-(void) myMethod;
-(void) twoManyMethod;


@end

ObjectVariable.m

//
//  ObjectVariable.m
//  LearnObjCPart2
//
//  Created by Kevin Languedoc on 1/17/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import "ObjectVariable.h"
#import "ToOneObject.h"

@implementation ObjectVariable
@synthesize stringVar;

-(void) myMethod{
    ToOneObject *leChiffre = [[ToOneObject alloc] init];
    [leChiffre numbers];
    
    vars =@"a value";
    
    int digits = defineAConst;
    
    int someOfDigits;
    
    someOfDigits = 2 * digits;
    
}

-(void)twoManyMethod{
    ToOneObject *lotsOfVars = [[ToOneObject alloc] init];
    [lotsOfVars addSomeVars:@"Test"];
 
}

@end

More by this Author


Comments 11 comments

phdast7 profile image

phdast7 4 years ago from Atlanta, Georgia

I voted Up. What a tremendous amount of work on your part. And although I have no idea what you are talking about, I am sure many other people do.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks phdast7. Thanks for your kind words and vote. I really appreciate them. indeed it is a lot of work, researching, writing and testing the code and then writing the hub, but I enjoy it and hopefully it will help a lot of new programmers learning Objecive-C.


John Sarkis profile image

John Sarkis 4 years ago from Los Angeles, CA

Excellent hub. You're so knowledgeable about computers, it's very intimidating for me being I'm not very computer literate....

Great hub

John


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks John. I really appreciate your kind words. I spend a lot of my time studying like any other endeavor.


Max Kareta 4 years ago

if you find this article helpful than I really recommend to read Objective-C Programming guide. You must have little reason when use @public, because you will break encapsulation.In additional when use defines don't forget about brackets, example

#define SomeConst 10+5

//usage

x*SomeConst+4 //you want this x * 15 + 4, but get x * 10 + 5 + 4 instead


zav 3 years ago

"The receivers instance variable"

receiver's instance variable

Your code needs to compile, so should your English.


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

Thanks for the typo catch. My code always compiles and is tested before publication.


Jake 3 years ago

Great article!

One small correction though - you declare a protected instance var NSNumber *numbers;

Then you declare a property to generate accessors to 'numbers.' So far is everything ok.

The error occurs when you declare @synthesize numbers = _numbers. What this does is tell the compiler to create another instance variable _numbers which the property will set/get via the generated accessors.

In other words, when the client code performs myObject.numbers = 1234; it's actually setting the iVar _numbers and NOT numbers as the author intends. In fact numbers is never used unless it's directly accessed by the class or any subclass! This can lead to some nasty bugs.


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

Hey Jake

Thanks so much for the info. I will update the code.

Kevin


bfilipek profile image

bfilipek 2 years ago from Cracow

Good hub. Programming in ios and objectiveC is sery popular right now. Why do you use pictures instead of code capsules? It seems to be more work that way.


klanguedoc profile image

klanguedoc 2 years ago from Canada Author

when I started writing on this platform, they didn't have code capsules.

    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