Last active
January 2, 2016 11:29
-
-
Save randomsequence/8296932 to your computer and use it in GitHub Desktop.
NSMapTable weakToStrongObjectsMapTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#if ! __has_feature(objc_arc) | |
#error This file must be compiled with ARC. | |
#endif | |
@interface Number : NSObject | |
@property (nonatomic, readonly) NSInteger integer; | |
+ (id)numberWithInteger:(NSInteger)integer; | |
- (id)initWithInteger:(NSInteger)integer; | |
@end | |
@implementation Number | |
+ (id)numberWithInteger:(NSInteger)integer { | |
return [[Number alloc] initWithInteger:integer]; | |
} | |
- (id)initWithInteger:(NSInteger)integer { | |
if (self == [super init]) { | |
_integer = integer; | |
} | |
return self; | |
} | |
- (void)dealloc { | |
NSLog(@"dealloc number %i", (int) _integer); | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
NSMapTable *mapTable = [NSMapTable weakToStrongObjectsMapTable]; | |
NSArray *keys = nil; | |
@autoreleasepool { | |
keys = [[NSArray alloc] initWithObjects:[Number numberWithInteger:1], [Number numberWithInteger:2], [Number numberWithInteger:3], nil]; | |
for (id key in keys) { | |
[mapTable setObject:[NSNull null] forKey:key]; | |
} | |
NSLog(@"%@", mapTable); | |
keys = nil; | |
} | |
[mapTable setObject:[NSNull null] forKey:@(4)]; | |
NSLog(@"%@", mapTable); | |
} | |
} | |
// Output | |
// | |
// 2014-01-07 09:52:22.269 Untitled[31334:507] NSMapTable { | |
// [1] <Number: 0x7f9ddbc07c50> -> <null> | |
// [2] <Number: 0x7f9ddbc083a0> -> <null> | |
// [3] <Number: 0x7f9ddbc0b020> -> <null> | |
// } | |
// 2014-01-07 09:52:22.271 Untitled[31334:507] dealloc number 1 | |
// 2014-01-07 09:52:22.271 Untitled[31334:507] dealloc number 2 | |
// 2014-01-07 09:52:22.272 Untitled[31334:507] dealloc number 3 | |
// 2014-01-07 09:52:22.272 Untitled[31334:507] NSMapTable { | |
// [1] 4 -> <null> | |
// } |
@mrwalker it should be, but first you need to compile the code with ARC.
it could be that the Integer objects are optimised to keep common numbers (i.e. lower numbers) around as global constants for a while. I know java does this, so that Integer (the object) does not need to be expensively re-instantiated every time you put a 4 into an array or dictionary.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't the 2nd log be an empty map table?