我试图使用NSHashTable来存储一些带有弱引用的对象指针。在学习过程中,我发现NSString(NSNumber)对象在插入[NSHashTable weakObjectsHashTable]后没有被释放。任何自定义的类都将起作用。
关于为什么NSString(NSNumber)对象没有被释放的任何想法?
#import <Foundation/Foundation.h>
@interface C : NSObject
@property(nonatomic) NSHashTable *hashTable;
@end
@implementation C
- (instancetype)init {
self = [super init];
if (self) {
_hashTable = [NSHashTable weakObjectsHashTable];
}
return self;
}
- (void)addObject:(NSObject *)obj {
[self.hashTable addObject:obj];
}
- (void)printAllObjects {
NSLog(@"Members: %@", [self.hashTable allObjects]);
[[self.hashTable allObjects] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%p\n", obj);
}];
}
+ (void)hi:(C *)c {
@autoreleasepool {
NSString *s;
for(int i=0; i<10000; i++) {
s = [[NSString alloc] initWithFormat:@"%d", i];
[c addObject:s];
}
}
}
@end
void hi(C *c) {
NSString *i = @"hi";
NSLog(@"%p", i);
[c addObject:i];
}
int main(int argc, char *argv[]) {
C *c = [[C alloc] init];
@autoreleasepool {
[C hi:c];
}
[c printAllObjects];
}
Xcode版本为8.1(8B62),输出为:
2016-12-12 11:16:30.361 0x7fff9106c920
2016-12-12 11:16:30.362 Members: (
""
)
2016-12-12 11:16:30.362 0x7fff9106c920