Skip to content

Instantly share code, notes, and snippets.

@trojanfoe
Created May 6, 2015 10:10
Show Gist options
  • Save trojanfoe/485de9f9851d4aac8854 to your computer and use it in GitHub Desktop.
Save trojanfoe/485de9f9851d4aac8854 to your computer and use it in GitHub Desktop.
Prefab Pool implementation
#import "PrefabPool.h"
#pragma mark - Private Interface
@interface PrefabPool ()
{
NSUInteger _nextIndex;
NSMutableArray *_pool;
}
@property (nonatomic) NSString *name;
@property (nonatomic) NSUInteger capacity;
@end
@implementation PrefabPool
#pragma mark - Class Methods
+ (PrefabPool *)prefabPoolWithPrefab:(NSString *)name
capacity:(NSUInteger)capacity
{
return [[PrefabPool alloc] initWithPrefab:name
capacity:capacity];
}
- (instancetype)initWithPrefab:(NSString *)name
capacity:(NSUInteger)capacity
{
self = [super init];
if (self) {
_nextIndex = 0;
_pool = [NSMutableArray new];
self.name = name;
self.capacity = capacity;
for (NSUInteger i = 0; i < capacity; i++) {
CCNode *prefab = [CCBReader load:name];
if (prefab) {
[_pool addObject:prefab];
} else {
logerr(@"Failed to load prefab '%@'", name);
self = nil;
break;
}
}
}
return self;
}
- (CCNode *)prefab
{
CCNode *prefab = (CCNode *)_pool[_nextIndex];
if (prefab.parent) {
logwrn(@"Prefab pool for '%@' overflowed", self.name);
[prefab removeFromParent];
}
_nextIndex = (_nextIndex + 1) % self.capacity;
return prefab;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment