0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RLMResults, RLMArrayでBlocksKitのようにmap, select, reject等を使いたい

0
Last updated at Posted at 2016-03-07

動機

Realmに触っていたときに、前から好きで使ってたBlocksKit のメソッドが使えなかったのでBlocksKitを参考にして拡張してみました。
最低限のメソッドしか実装してないですがあしからず

ゴール

RLMResults *result = [RLMObject objectsWhere:@"id < 10"];
[results bk_map:^id(id obj){ block }];

のように使いたい。

拡張 (RLMResults+Block.m)

- (void)rlm_each:(void (^)(id obj))block;
{
    NSParameterAssert(block != nil);
    for (id obj in self) {
        block(obj);
    }
}

- (void)rlm_eachWithIndex:(void (^)(id obj, int idx))block
{
    NSParameterAssert(block != nil);
    
    int index = 0;
    for (id obj in self) {
        block(obj, index);
        index++;
    }
}

- (id)rlm_match:(BOOL (^)(id obj))block;
{
    NSParameterAssert(block != nil);
    
    for (id obj in self) {
        if (block(obj)) {
            return obj;
            break;
        }
    }
    
    // not match
    return nil;
}

- (NSArray *)rlm_map:(id (^)(id obj))block
{
    NSParameterAssert(block != nil);
    NSMutableArray *result = [NSMutableArray array];
    
    for (id it in self) {
        id value = block(it) ?: [NSNull null];
        [result addObject:value];
    }
    
    return result;
}

拡張 (RLMArray+Block.m)

- (void)rlm_each:(void (^)(id obj))block
{
    NSParameterAssert(block != nil);
    
    for (id obj in self) {
        block(obj);
    }
}

- (void)rlm_eachWithIndex:(void (^)(id obj, int idx))block
{
    NSParameterAssert(block != nil);
    
    int index = 0;
    for (id obj in self) {
        block(obj, index);
        index++;
    }
}

- (id)rlm_match:(BOOL (^)(id obj))block
{
    NSParameterAssert(block != nil);
    
    for (id obj in self) {
        if (block(obj)) {
            return obj;
            break;
        }
    }
    
    // not match
    return nil;
}

- (NSArray *)rlm_map:(id (^)(id obj))block
{
    NSParameterAssert(block != nil);
    
    NSMutableArray *result = [NSMutableArray array];
    for (id obj in self) {
        id value = block(obj) ?: [NSNull null];
        [result addObject:value];
    }
    
    return result;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?