Contents

Composite Objects in Objective-C

Composite Objects in Objective-C

In Objective-C, composite objects refer to objects made up of other objects. This implies that an object can have other objects as its instance variables or can itself be a part of another object’s instance variables.

Composite objects are incredibly useful when creating complex data structures. For example, a user interface with multiple components can be represented through composite objects. Similarly, composite objects are valuable in designing games with multiple levels, enemies, or weapons.

Types of Composite Objects

1. NSArray

NSArray is a class in Objective-C that represents an ordered collection of objects. It stores and retrieves a list of objects in a linear sequence, each assigned an index number starting from zero.

Syntax:

				
					NSArray *array = [[NSArray alloc] initWithObjects:object1, object2, object3, ..., nil];  

				
			
  • NSArray is the class name.
  • array is the instance of the class.
  • alloc allocates memory for the array.
  • initWithObjects initializes the array with the provided objects.
  • object1, object2, object3, etc., are the objects stored in the array.
  • nil indicates the end of the list.

Example:

				
					#import <Foundation/Foundation.h>  

int main(int argc, const char * argv[]) {  
    @autoreleasepool {  
        // Create an array of fruit names  
        NSArray *fruits = @[@"Apple", @"Mango", @"Banana", @"Grapes"];  

        // Display each fruit in the array  
        for (NSString *fruit in fruits) {  
            NSLog(@"%@", fruit);  
        }  
    }  
    return 0;  
}  

				
			

Approach:
Here, an NSArray object named fruits is created, containing four strings: “Apple”, “Mango”, “Banana”, and “Grapes”. Each string is printed to the console using NSLog.

Output:

				
					Apple  
Mango  
Banana  
Grapes  

				
			
2. NSDictionary

NSDictionary is a class in Objective-C that stores collections of key-value pairs, akin to an associative array or map. Keys uniquely identify each value and must conform to the NSCopying protocol. The class provides numerous methods to manipulate and retrieve data.

Syntax:

				
					NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:  
                            value1, key1,  
                            value2, key2,  
                            value3, key3,  
                            nil];  

				
			
  • initWithObjectsAndKeys initializes the dictionary with key-value pairs.
  • Each key-value pair is represented by two consecutive arguments.

Example:

				
					#import <Foundation/Foundation.h>  

int main(int argc, const char * argv[]) {  
    @autoreleasepool {  
        // Create a dictionary of student details  
        NSDictionary *studentInfo = [[NSDictionary alloc] initWithObjectsAndKeys:  
                                      @"John", @"name",  
                                      @"21", @"age",  
                                      @"Computer Science", @"major",  
                                      nil];  

        // Access values in the dictionary  
        NSString *name = [studentInfo objectForKey:@"name"];  
        NSString *age = [studentInfo objectForKey:@"age"];  
        NSString *major = [studentInfo objectForKey:@"major"];  

        // Print the values  
        NSLog(@"Name: %@", name);  
        NSLog(@"Age: %@", age);  
        NSLog(@"Major: %@", major);  
    }  
    return 0;  
}  

				
			

Approach:
Here, an NSDictionary object named studentInfo is created with three key-value pairs: "name"-"John", "age"-"21", and "major"-"Computer Science". Values are retrieved using the objectForKey: method and displayed using NSLog.

Output:

				
					Name: John  
Age: 21  
Major: Computer Science  

				
			
3. NSSet

NSSet is a collection class that stores an unordered set of unique objects. Unlike arrays, sets do not maintain order, and duplicate objects are not allowed. You can create an NSSet using the setWithObjects: method.

Syntax:

				
					NSSet *mySet = [NSSet setWithObjects:obj1, obj2, obj3, ..., nil];  

				
			

Example:

				
					#import <Foundation/Foundation.h>  

int main(int argc, const char * argv[]) {  
    @autoreleasepool {  
        // Create a set of vehicle types  
        NSSet *vehicles = [NSSet setWithObjects:@"Car", @"Bike", @"Truck", nil];  

        // Display each vehicle in the set  
        for (NSString *vehicle in vehicles) {  
            NSLog(@"%@", vehicle);  
        }  

        // Check if a specific object exists in the set  
        BOOL containsBike = [vehicles containsObject:@"Bike"];  
        if (containsBike) {  
            NSLog(@"The set contains Bike");  
        } else {  
            NSLog(@"The set does not contain Bike");  
        }  
    }  
    return 0;  
}  

				
			

Approach:
Here, an NSSet object named vehicles is created with three strings: “Car”, “Bike”, and “Truck”. Each string is printed using a loop. The containsObject: method is used to check if “Bike” exists in the set.

Output:

				
					Car  
Bike  
Truck  
The set contains Bike