Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Working with NSDictionary and NSMutableDictionary in Foundation Framework

Notes Sep 29 16

NSDictionary Overview

NSDictionary provides key-value storage where each unique key maps to a corresponding value. Unlike mutable variants, NSDictionary instances are immutable after initialziation.

Creating NSDictionary

// Empty dictionary
NSDictionary *emptyDict = [NSDictionary dictionary];

// Single key-value pair
NSDictionary *singlePair = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];

// Multiple key-value pairs
NSDictionary *multiPair = @{@"key1": @"value1", @"key2": @"value2"};

Basic Operations

// Count elements
NSUInteger count = [dictionary count];

// Retrieve value
id value = [dictionary objectForKey:@"key"];

Iterating Through NSDictionary

// Fast enumeration
for (NSString *key in dictionary) {
    id value = dictionary[key];
    NSLog(@"%@ => %@", key, value);
}

// Block enumeration
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"%@ => %@", key, obj);
}];

File Operations

// Write to file
[dictionary writeToFile:@"/path/to/file.plist" atomically:YES];

// Read from file
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/path/to/file.plist"];

NSMutableDictionary Basics

NSMutableDictionary extends NSDictionary with mutability, allowing dynamic modification of contents after creation.

Common Mutating Methods

// Add/modify value
[mutableDict setObject:@"newValue" forKey:@"key"];

// Remove value
[mutableDict removeObjectForKey:@"key"];

// Clear all
[mutableDict removeAllObjects];

Dictionary vs Array Comparison

Key differences:

  1. NSArray maintains order, NSDictionary doesn't
  2. Arrays use indices, dictionaries use keys
// Array example
NSArray *array = @[@"item1", @"item2"];
id item = array[0];

// Dictionary example
NSDictionary *dict = @{@"key1": @"value1", @"key2": @"value2"};
id value = dict[@"key1"];

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.