Last active
December 20, 2015 09:58
-
-
Save satoshin2071/6111738 to your computer and use it in GitHub Desktop.
objective-c blocks Practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSArray *before = @[ @"hoge", @"fuga", @"piyo", @1, @2, @3, @"foo", @"bar"]; | |
NSArray *after = [before grep:^BOOL(id obj) {return [obj isKindOfClass:[NSString class]];}]; | |
NSLog(@"%@", after); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSArray (grep) | |
- (NSArray *)grep:(BOOL(^)(id))block; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSArray+grep.h" | |
@implementation NSArray (grep) | |
- (NSArray *)grep:(BOOL(^)(id))block | |
{ | |
NSMutableArray *newArray = [NSMutableArray array]; | |
[self enumerateObjectsUsingBlock:^(id item,NSUInteger idx,BOOL *stop){ | |
//引数で渡されたblockを実行して戻り値のBOOLを格納 | |
BOOL obj = block(item); | |
//blockの実行結果が真なら配列に追加 | |
if (obj) { | |
[newArray addObject:item]; | |
} | |
}]; | |
return newArray; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment