Skip to content

Instantly share code, notes, and snippets.

@evadne
Created May 10, 2011 19:28
Show Gist options
  • Save evadne/965194 to your computer and use it in GitHub Desktop.
Save evadne/965194 to your computer and use it in GitHub Desktop.
Shared instances for all
2011-05-11 03:25:07.462 GlobalSingletonSupportTest[63618:1803] irSharedInstance instance NSObject 15f980, 181511 ns
2011-05-11 03:25:07.465 GlobalSingletonSupportTest[63618:5303] irSharedInstance instance NSObject 15f980, 614 ns
2011-05-11 03:25:07.465 GlobalSingletonSupportTest[63618:5403] irSharedInstance instance NSObject 15f980, 584 ns
2011-05-11 03:25:07.464 GlobalSingletonSupportTest[63618:a0f] irSharedInstance instance NSObject 15f980, 1546 ns
2011-05-11 03:25:07.466 GlobalSingletonSupportTest[63618:a0f] irSharedInstance instance NSObject 15f980, 1545 ns
//
// NSObject+IRSharedInstance.h
// GlobalSingletonSupportTest
//
// Created by Evadne Wu on 5/11/11.
// Copyright 2011 Iridia Productions. All rights reserved.
//
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
extern NSString * const kIRSharedInstancePredicate;
extern NSString * const kIRSharedInstanceObject;
@interface NSObject (IRSharedInstance)
+ (id) irSharedInstance;
@end
//
// NSObject+IRSharedInstance.m
// GlobalSingletonSupportTest
//
// Created by Evadne Wu on 5/11/11.
// Copyright 2011 Iridia Productions. All rights reserved.
//
#import "NSObject+IRSharedInstance.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <unistd.h>
NSString * const kIRSharedInstancePredicate = @"IRSharedInstance_Predicate";
NSString * const kIRSharedInstanceObject = @"IRSharedInstance_Object";
@implementation NSObject (IRSharedInstance)
+ (id) irSharedInstance {
// uint64_t begin = mach_absolute_time();
__block dispatch_once_t predicate = 0;
__block id returned = objc_getAssociatedObject(self, kIRSharedInstanceObject);
if (!returned) @synchronized(self) {
returned = objc_getAssociatedObject(self, kIRSharedInstanceObject);
if (!returned) {
[(NSValue *)objc_getAssociatedObject(self, kIRSharedInstancePredicate) getValue:&predicate];
dispatch_once(&predicate, ^ {
returned = [[self alloc] init];
objc_setAssociatedObject(self, kIRSharedInstanceObject, returned, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject(self, kIRSharedInstancePredicate, [NSValue valueWithBytes:&predicate objCType:@encode(__typeof__(predicate))], OBJC_ASSOCIATION_RETAIN);
});
}
}
// uint64_t end = mach_absolute_time();
// NSLog(@"irSharedInstance instance %@ %x, %i ns", NSStringFromClass([returned class]), returned, (end - begin));
return returned;
}
@end
@evadne
Copy link
Author

evadne commented May 10, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment