集装箱下标
在现代 Objective C 语法中,你可以使用容器下标从 NSArray
和 NSDictionary
容器中获取值。
旧方式:
NSObject *object1 = [array objectAtIndex:1];
NSObject *object2 = [dictionary objectForKey:@"Value"];
现代方式:
NSObject *object1 = array[1];
NSObject *object2 = dictionary[@"Value"];
你还可以以更清晰的方式将对象插入到数组中并为字典中的键设置对象:
旧方式:
// replacing at specific index
[mutableArray replaceObjectAtIndex:1 withObject:@"NewValue"];
// adding a new value to the end
[mutableArray addObject:@"NewValue"];
[mutableDictionary setObject:@"NewValue" forKey:@"NewKey"];
现代方式:
mutableArray[1] = @"NewValue";
mutableArray[[mutableArray count]] = @"NewValue";
mutableDictionary[@"NewKey"] = @"NewValue";