ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on May 8, 2013
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building software applications including iOS and Android apps.

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

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      4 years ago from Canada

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

    • profile image

      bfilipek 

      4 years ago

      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 imageAUTHOR

      Kevin Languedoc 

      4 years ago from Canada

      Hey Jake

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

      Kevin

    • profile image

      Jake 

      4 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 imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

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

    • profile image

      zav 

      5 years ago

      "The receivers instance variable"

      receiver's instance variable

      Your code needs to compile, so should your English.

    • profile image

      Max Kareta 

      6 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

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

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

    • John Sarkis profile image

      John Sarkis 

      6 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 imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      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.

    • phdast7 profile image

      Theresa Ast 

      6 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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)