NSArray
声明了一个私有 ivar _used
,它似乎保存了数组的计数。使用object_getInstanceVariable()
您可以验证在具体子类的情况下__NSArrayM
,此变量会随着对象的添加和删除而递增和递减。
我使用以下程序(Mac OS X Foundation 命令行工具)来验证这一点:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *anArray = [NSMutableArray array];
NSLog(@"anArray's concrete class is %@", [anArray class]);
UInt64 used = 0;
for (NSString *toAdd in @[@"o", @"m", @"g"]) {
object_getInstanceVariable(anArray, "_used", (void **)&used);
NSLog(@"array = %@, used = %lld", anArray, used);
[anArray addObject:toAdd];
}
for (NSString *toRemove in [anArray copy]) {
object_getInstanceVariable(anArray, "_used", (void **)&used);
NSLog(@"array = %@, used = %lld", anArray, used);
[anArray removeObject:toRemove];
}
object_getInstanceVariable(anArray, "_used", (void **)&used);
NSLog(@"array = %@, used = %lld", anArray, used);
}
return 0;
}
该程序产生以下输出:
2013-01-31 17:40:15.376 Array[10173:303] anArray's concrete class is __NSArrayM
2013-01-31 17:40:15.378 Array[10173:303] array = (
), used = 0
2013-01-31 17:40:15.378 Array[10173:303] array = (
o
), used = 1
2013-01-31 17:40:15.379 Array[10173:303] array = (
o,
m
), used = 2
2013-01-31 17:40:15.379 Array[10173:303] array = (
o,
m,
g
), used = 3
2013-01-31 17:40:15.380 Array[10173:303] array = (
m,
g
), used = 2
2013-01-31 17:40:15.380 Array[10173:303] array = (
g
), used = 1
2013-01-31 17:40:15.380 Array[10173:303] array = (
), used = 0