Skip to content

Instantly share code, notes, and snippets.

@koogawa
Created March 12, 2014 02:41
Show Gist options
  • Save koogawa/9499795 to your computer and use it in GitHub Desktop.
Save koogawa/9499795 to your computer and use it in GitHub Desktop.
Objective-Cのいろいろな反復処理
- (void)test
{
NSArray *anArray = @[@"a", @"b", @"c"];
NSDictionary *aDictionary = @{@"key1": @"val1",
@"key2": @"val2",
@"key3": @"val3"};
// for loop
for (int i = 0; i < anArray.count; i++)
{
id object = anArray[i];
NSLog(@"object = %@", object);
}
NSArray *keys = [aDictionary allKeys];
for (int i = 0; i < keys.count; i++)
{
id key = keys[i];
id value = aDictionary[key];
NSLog(@"key = %@, value = %@", key, value);
}
// 高速反復処理
for (id object in anArray)
{
NSLog(@"object = %@", object);
}
for (id object in [anArray reverseObjectEnumerator])
{
NSLog(@"object = %@", object);
}
for (id key in aDictionary)
{
id value = aDictionary[key];
NSLog(@"key = %@, value = %@", key, value);
}
// blocks
[anArray enumerateObjectsUsingBlock:
^(NSString *object, NSUInteger idx, BOOL *stop) {
NSLog(@"object = %@, idx = %lu", object, (unsigned long)idx);
}];
[anArray enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:
^(NSString *object, NSUInteger idx, BOOL *stop) {
NSLog(@"object = %@, idx = %lu", object, (unsigned long)idx);
}];
[aDictionary enumerateKeysAndObjectsUsingBlock:
^(id key, id object, BOOL *stop) {
NSLog(@"key = %@, object = %@", key, object);
}];
[aDictionary enumerateKeysAndObjectsWithOptions:NSEnumerationReverse
usingBlock:
^(id key, id object, BOOL *stop) {
NSLog(@"key = %@, object = %@", key, object);
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment