Lazy datatypes in Objective C

放肆的年华 提交于 2019-12-04 07:50:55

Cool question!

You could implement a lazy container in Objective-C as follows (but you probably shouldn't, see below):

typedef id (^SuspBlock)(void);

@interface Susp : NSObjecti
- (id)initWithBlock:(SuspBlock)block;
+ (id)withBlock:(SuspBlock)block;
- (id)force;
@end

// -----

@interface Susp ()
@property (nonatomic, copy) SuspBlock _block;
@end

@implementation Susp
@synthesize _block;

- (id)initWithBlock:(SuspBlock)block {
  self = [super init];
  if (self != nil) {
    self._block = block;
  }

  return self
}

+ (id)withBlock:(SuspBlock)block {
  return [[[self alloc] initWithBlock:bloc] autorelease];
}

- (id)force {
  return self._block();
}

- (void)dealloc {
 self._block = nil;
 [super dealloc];
}

@end

That's a lot of boilerplate, but whatever. Then, you could use it like this:

id x = [Susp withBlock:^{ return someComputation(); }];
id result = [[x force] plus:[x force]];
// assuming the result of your computation has -plus:

But that's all rather silly, since for what you're doing, you really don't need another data type. Just use blocks as your datatype:

typedef id (^SuspVal)(void);
SuspVal x = ^{ return complicatedThing; };
id result = [x() plus:x()];

That's a much more compact, idiomatic way of going about it, and it's what I suggest. Unless you need to add further semantics to your lazy objects that go beyond the basic utilities of blocks, you shouldn't wrap them needlessly.

Cheers!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!