Open In App

Composite Objects in Objective-C

Last Updated : 14 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Objective-C, composite objects are objects that are composed of other objects. This means that an object can have one or more objects as its instance variables, and it can also be a part of another object’s instance variables.

Composite objects are useful in many scenarios where complex data structures are required. For instance, a complex user interface that has multiple components can be represented using composite objects. Similarly, a game that has multiple levels, enemies, and weapons can also use composite objects.

Types of Composite Objects 

1.  NSArray

NSArray is a class in Objective-C that represents an ordered collection of objects. It is used to store and retrieve a list of objects of the same type. The objects are stored in a linear sequence, and each object is 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 name of the instance of the class.

‘alloc’ is a class method that allocates memory for the array.

‘ initWithObjects’ is an instance method that initializes the array with the specified objects.

‘object1’, ‘object2‘, ‘object3’, … are the objects to be stored in the array.

‘nil’ is a sentinel value that marks the end of the list of objects.

 Example:

ObjectiveC




#import <Foundation/Foundation.h>
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
          
        // Create an array of NSString objects
        NSArray *vegetables = @[@"Brinjal", @"Onion", @"Cabbage", @"Potato"];
          
        // Print out each vegetable in the array
        for (NSString *vegetable in vegetables) {
            NSLog(@"%@", vegetable);
        }
          
    }
    return 0;
}


Approach: In this example, we create an NSArray object called array that contains four string objects: “Brinjal”, “Onion”, “Cabbage” and “Potato”. And print the results using NSLog().

Output:

output

 

2. NSDictionary

NSDictionary is a class in Objective-C that is used to store collections of key-value pairs, also known as an associative array or a map. The keys are used to uniquely identify each value, and they can be any object that conforms to the ‘NSCopying’ protocol. It provides a number of methods to manipulate and retrieve data from the collection.

Syntax:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:

                            value1, key1,

                            value2, key2,

                            value3, key3,

                            nil];

In the above syntax, ‘initWithObjectsAndKeys’ is the initializer method that creates an instance of NSDictionary. It takes a variable number of arguments, where each key-value pair is represented by two consecutive arguments.

Example:

ObjectiveC




#import <Foundation/Foundation.h>
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
          
        // Create an instance of NSDictionary
        NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    @"XYZ", @"firstName",
                                    @"abc", @"lastName",
                                    @"30", @"age",
                                    nil];
          
        // Access values in the dictionary
        NSString *firstName = [dictionary objectForKey:@"firstName"];
        NSString *lastName = [dictionary objectForKey:@"lastName"];
        NSNumber *age = [dictionary objectForKey:@"age"];
          
        // Print the values
        NSLog(@"First name: %@", firstName);
        NSLog(@"Last name: %@", lastName);
        NSLog(@"Age: %@", age);
          
        // Add a new key-value pair to the dictionary
        [dictionary setValue:@"New York" forKey:@"city"];
          
        // Print the updated dictionary
        NSLog(@"Dictionary: %@", dictionary);
    }
    return 0;
}


Approach: In this example, we create an instance of NSDictionary with three key-value pairs: “firstName”-“XYZ”, “lastName”-“abc”, and “age”-“30”. We then access these values using the objectForKey: method and print them to the console using NSLog.

We also add a new key-value pair to the dictionary using the setValue:forKey: method and print the updated dictionary using NSLog.

Output:

output

 

3. NSSet

NSSet is a collection class that stores an unordered set of unique objects. It is similar to an array, but unlike arrays, sets do not store objects in a specific order, and they can only contain unique objects. To create an NSSet, you can use the setWithObjects: method, which takes a variable number of arguments. One real-life example of NSSet in Objective-C is in a music streaming application.

Syntax:

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

This creates an NSSet object mySet containing the objects ‘obj1’, ‘obj2‘, ‘obj3‘, and so on. The last argument to the method is nil, indicating the end of the argument list.

ObjectiveC




#import <Foundation/Foundation.h>
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
          
        // Create a set of NSString objects
        NSSet *stringSet = [NSSet setWithObjects:@"Apple", @"Banana", @"Cherry", nil];
          
        // Loop through the set and print each string
        for (NSString *string in stringSet) {
            NSLog(@"%@", string);
        }
          
        // Check if the set contains a specific object
        BOOL containsApple = [stringSet containsObject:@"Apple"];
        if (containsApple) {
            NSLog(@"The set contains Apple");
        } else {
            NSLog(@"The set does not contain Apple");
        }
          
    }
    return 0;
}


Approach: In this example, we first create a set of NSString objects using the setWithObjects: method. We then loop through the set using a for-in loop and print each string to the console using NSLog. Finally, we check if the set contains the string “Apple” using the containsObject: method and print a message to the console depending on the result.

Output:

output

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads