What are structures in Objective-C?
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;..}// ORstruct 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
#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;}
Explanation
- Line 2: We define the structure by using
struct followed by the nameReserved keyword for structures in objective c Drinks{}. - Lines 3-5: We define the members of the structure. It is the information we want to store in the
Drinksstruct:Drink_name,Size, anddrink_id. - Line 6: The end of
struct Drinksis followed by curly braces and a semicolon,;. - Lines 9-10: We create two objects
mydrink1andmydrink2of the typeDrinks. - Lines 12-14: We set values for the
mydrink1object—its name, size, and ID. - Lines 16-18: We set values for the
mydrink2object—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.