Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

objective c

What are structures in Objective-C?

Salman Yousaf

Overview

We usually use arrays to hold information. However, in the Objective-C language, there is another way of performing the same task, commonly known as structures. Structures allow users to define their own data items that can be a combination of different data types.

Syntax

struct{
    member 1;
    member 2;
    .
    .
}
// OR
struct variables(/*optional*/);

A struct is a user-defined data type that allows storing different kinds of information. It can be used to store various records of books, students, flight details, and so on.

Example

Let's explain the Objective-C struct Structurein detail:

#import <Foundation/Foundation.h>
struct Drinks{
   NSString *Drink_name;
   NSString *Size;
   int drink_id;
};
int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   struct Drinks mydrink1;
   struct Drinks mydrink2;

   mydrink1.Drink_name = @"Strawberry Icecream Shake";
   mydrink1.Size = @"Medium";
   mydrink1.drink_id = 10;

   mydrink2.Drink_name = @"Oreo Shake";
   mydrink2.Size = @"Large";
   mydrink2.drink_id = 12;

   NSLog( @"Shake#1 Name : %@\n", mydrink1.Drink_name);
   NSLog( @"Shake#1  Size : %@\n", mydrink1.Size);
   NSLog( @"Shake#1 Id: %d\n", mydrink1.drink_id);
   NSLog( @"Shake#2 Name: %@\n", mydrink2.Drink_name);
   NSLog( @"Shake#2 Size:%@\n", mydrink2.Size);
   NSLog( @"Shake#2 Id: %d\n", mydrink2.drink_id);
   [pool drain];
   return 0;
}
Using struct in Objective-C

Explanation

  • Line 2: We define the structure by using struct Reserved keyword for structures in objective cfollowed by the name Drinks{}.
  • Lines 3-5: We define the members of the structure. It is the information we want to store in the Drinks struct: Drink_name, Size, and drink_id.
  • Line 6: The end of struct Drinks is followed by curly braces and a semicolon, ;.
  • Lines 9-10: We create two objects mydrink1 and mydrink2 of the type Drinks.
  • Lines 12-14: We set values for the mydrink1 object—its name, size, and ID.
  • Lines 16-18: We set values for the mydrink2 object—its name, size, and ID.

Note: We can use the scope resolution operator, ., to access member variables. For example, mydrink1.Size=@"Medium";

  • Lines 20-25: We print the values by using the NSLog() function on console.

RELATED TAGS

objective c
RELATED COURSES

View all Courses

Keep Exploring