Skip to content

Instantly share code, notes, and snippets.

+ (id)sharedWhatever
{
static Whatever *whatever = nil;
if( !whatever )
{
Whatever *newWhatever = [[self alloc] init];
if( !OSAtomicCompareAndSwapPtrBarrier( nil, newWhatever, (void *)&whatever ) )
{
[newWhatever release];
}
+ (id)sharedInstance {
id singleton = objc_getAssociatedObject(...);
if(!singleton) {
[lock lock];
singleton = objc_getAssociatedObject(...);
if(!singleton)
objc_setAssociatedObject([[self alloc] init], ...);
[lock unlock];
}
}
#define BIT_SET(array, bit) (array[bit / 8] |= (1 << (bit % 8)))
#define BIT_CLEAR(array, bit) (array[bit / 8] &= ~(1 << (bit % 8)))
#define BIT_GET(array, bit) ((array[bit / 8] | (1 << (bit % 8))) != 0)
uint8_t array[5];
bzero(array, sizeof(array);
BIT_SET(array, 18);
BIT_GET(array, 18);
#import <Foundation/Foundation.h>
#import <pthread.h>
typedef void (^MyBlock)(void);
typedef void (*MyFunc)(void *);
static void Block(MyBlock block)
{
NSLog(@"Block called with %p", block);
}
@mikeash
mikeash / gist:781000
Created January 15, 2011 16:08
dirty error example
- (id)fooWithError: (NSError **)outError
{
id obj = [self barWithThing: @"thing" error: outError];
if(!obj)
obj = [self quuxWithThing: @"thing" error: outError];
return obj;
}
@mikeash
mikeash / gist:837409
Created February 21, 2011 17:47
Block-based URL connection
// NSURLConnection wrapper
// like NSURLConnection, requires a runloop, callbacks happen in runloop that set up load
@interface LDURLLoader : NSObject
{
NSURLConnection *_connection;
NSTimeInterval _timeout;
NSTimer *_timeoutTimer;
NSURLResponse *_response;
long long _responseLengthEstimate;
NSMutableData *_accumulatedData;
@mikeash
mikeash / gist:1132620
Created August 8, 2011 20:17
Namespaced constants in C
#import <Foundation/Foundation.h>
// .h file
struct MyConstantsStruct
{
NSString *foo;
NSString *bar;
@mikeash
mikeash / NSFileReference.h
Created September 5, 2011 14:59
A basic sketch of an NSFileReference class interface
@interface NSFileReference : NSObject {
// internal storage would probably be NSURL, but could be
// NSString holding a path, FSRef, alias data, whatever
}
- (id)initWithPath: (NSString *)path;
- (id)initWithFileSystemRepresentation: (const char *)path;
- (id)initWithFSRef: (FSRef *)ref;
- (id)initWithAliasData: (NSData *)data;
- (id)initWithURL: (NSURL *)url;
dispatch_block_t RecursiveBlock(void (^block)(dispatch_block_t recurse))
{
// assuming ARC, so no explicit copy
return ^{ block(RecursiveBlock(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock RecursiveBlock1(void (^block)(OneParameterBlock recurse, id parameter))
{
@mikeash
mikeash / gist:1264419
Created October 5, 2011 13:28
Ideas for with blocks for weak variables
// function
void with(id obj, void (^block)(id obj))
{
block(obj);
}
// example use
with(blah, ^(Blah *blah) {
// use blah here
});