Skip to content

Commit

Permalink
Add GCReusableQueue
Browse files Browse the repository at this point in the history
  • Loading branch information
GlennChiu committed Jun 8, 2012
1 parent 472b6fe commit 126c614
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 0 deletions.
27 changes: 27 additions & 0 deletions GCReusableQueue/GCReusableQueue.h
@@ -0,0 +1,27 @@
//
// GCReusableQueue.h
// GCReusableQueue
//
// Created by Glenn Chiu on 31-05-12.
// Copyright (c) 2012 Dot Square. All rights reserved.
//

#import <Foundation/Foundation.h>

/* Make sure that objects conform to this protocol and return -reuseIdentifier. */
@protocol ReusableObject <NSObject>

- (NSString *)reuseIdentifier;

@end

@interface GCReusableQueue : NSObject

- (void)enqueueReusableObject:(id <ReusableObject>)obj;
- (id <ReusableObject>)dequeueReusableObjectWithIdentifier:(NSString *)identifier;

/* This method should not be used, as the queue will discard objects automatically
when memory gets tight. Use this method to discard objects manually. */
- (void)clearQueue;

@end
94 changes: 94 additions & 0 deletions GCReusableQueue/GCReusableQueue.m
@@ -0,0 +1,94 @@
//
// GCReusableQueue.m
// GCReusableQueue
//
// Created by Glenn Chiu on 31-05-12.
// Copyright (c) 2012 Dot Square. All rights reserved.
//

#import "GCReusableQueue.h"
#import <TargetConditionals.h>

@implementation GCReusableQueue
{
NSCache *_reusableObjects;
id _observer;
}

- (id)init
{
self = [super init];
if (self)
{

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR

__weak GCReusableQueue *w_self = self;

self->_observer = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
GCReusableQueue *s_self = w_self;

[s_self clearQueue];
}];

#endif

}
return self;
}

- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self->_observer];
}

- (NSCache *)reusableObjects
{
if (!self->_reusableObjects)
{
self->_reusableObjects = [NSCache new];
}

return self->_reusableObjects;
}

- (id <ReusableObject>)dequeueReusableObjectWithIdentifier:(NSString *)identifier
{
NSParameterAssert(identifier);

NSMutableSet *objects = [[self reusableObjects] objectForKey:identifier];

id <ReusableObject> obj = [objects anyObject];

if (obj)
{
[objects removeObject:obj];
}

return obj;
}

- (void)enqueueReusableObject:(id <ReusableObject>)obj
{
NSMutableSet *objects = [[self reusableObjects] objectForKey:[obj reuseIdentifier]];

if (!objects)
{
objects = [NSMutableSet set];
[[self reusableObjects] setObject:objects forKey:[obj reuseIdentifier]];
}
else
{
[objects addObject:obj];
}
}

- (void)clearQueue
{
[[self reusableObjects] removeAllObjects];
}

@end

0 comments on commit 126c614

Please sign in to comment.