Skip to content

Instantly share code, notes, and snippets.

@iwill
Last active December 22, 2015 10:58
Show Gist options
  • Select an option

  • Save iwill/6462268 to your computer and use it in GitHub Desktop.

Select an option

Save iwill/6462268 to your computer and use it in GitHub Desktop.
Use ARC Weak Reference in MRC file.
//
// ARCWeakRef.h
// M9
//
// Created by iwill on 2013-07-08.
// Copyright (c) 2013年 iwill. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* Usage:
* weakifyself;
* [object setCallback:^{
* strongifyself;
* NSLog(@"self: %@", self);
* }];
* OR
* __typeof__(self) selfType;
* ARCWeakRef *weakRef = [ARCWeakRef weakRefWithObject:self];
* [object setCallback:^{
* __typeof__(selfType) self = weakRef.object
* NSLog(@"self: %@", self);
* }];
*/
#define weakifyself __typeof__(self) $selfType; ARCWeakRef *$weakRef = [ARCWeakRef weakRefWithObject:self]
#define strongifyself __typeof__($selfType) self = $weakRef.object
@interface ARCWeakRef : NSObject
@property (weak, nonatomic) id object;
// - (instancetype)initWithObject:(id)object;
+ (instancetype)weakRefWithObject:(id)object;
@end
//
// ARCWeakRef.m
// M9
//
// Created by iwill on 2013-07-08.
// Copyright (c) 2013年 iwill. All rights reserved.
//
#import "ARCWeakRef.h"
#if ! __has_feature(objc_arc)
// set -fobjc-arc flag: - Target > Build Phases > Compile Sources > ARCWeakRef.m + -fobjc-arc
#error This file must be compiled with ARC. Use -fobjc-arc flag or convert project to ARC.
#endif
#if ! __has_feature(objc_arc_weak)
#error ARCWeakRef does not support iOS 4 and lower
#endif
@implementation ARCWeakRef
- (instancetype)initWithObject:(id)object {
self = [super init];
if (self) {
self.object = object;
}
return self;
}
+ (instancetype)weakRefWithObject:(id)object {
return [[self alloc] initWithObject:object];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment