خرید بک لینک

Vote count: 0

Today I have done an interesting experiment about reference count and memory organizing,but I get some confused.First,let's see the string code:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSString *str1 = [NSString stringWithString:@"string1"];
    // print reference count
    NSLog(@"%@ retainCount:%lu", str1, [str1 retainCount]);
    // print the size str1 pointed (only in heap)
    NSLog(@"%@ size:%zd", str1, malloc_size((__bridge const void *) str1)); 

    NSMutableString *str2 = [[NSMutableString alloc] initWithString:@"bar"];
    NSLog(@"%@ retainCount:%lu", str2, [str2 retainCount]);
    NSLog(@"%@ size:%zd", str2, malloc_size((__bridge const void *) str2));
}

After I touch the view,the console print this:

2016-06-23 15:51:45.608 dongguatest[10957:1065768] string1 retainCount:18446744073709551615
2016-06-23 15:51:45.609 dongguatest[10957:1065768] string1 size:0

2016-06-23 15:51:45.609 dongguatest[10957:1065768] bar retainCount:1
2016-06-23 15:51:45.609 dongguatest[10957:1065768] bar size:64

Everything done well.

Because String1 is immutable and stored in static data area,so its reference count is UINT_MAX.And string1 have no size allocated in heap.If you don't understand,you can see this.

String2 is a mutable String,OS allocated it in heap and it has a sizeof 64bytes.

So I think immutable thing will store in Static Data Area,and mutable thing will store in Heap Area.

But some strange thing happen about NSArray and I can't understand why it was happen after reading the Apple document.

NSArray code is below:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    NSArray *arr0 = [[NSArray alloc] init];
    NSLog(@"%@ retainCount:%lu", arr0, [arr0 retainCount]);
    NSLog(@"%@ size:%zd", arr0, malloc_size((__bridge const void *) arr0));


    NSMutableArray *arr1 = [[NSMutableArray alloc] init];
    NSLog(@"%@ retainCount:%lu", arr1, [arr1 retainCount]);
    NSLog(@"%@ size:%zd", arr1, malloc_size((__bridge const void *) arr1));
}

Console print below:

2016-06-23 16:10:58.239 dongguatest[11382:1144771] (
) retainCount:18446744073709551615
2016-06-23 16:10:58.240 dongguatest[11382:1144771] (
) size:16

2016-06-23 16:10:58.240 dongguatest[11382:1144771] (
) retainCount:1
2016-06-23 16:10:58.240 dongguatest[11382:1144771] (
) size:48

My question is,I could understand the information of NSMutableArray.But,why immutable array have a UINT_MAX reference count but also has 16 bytes size in heap?

asked 7 secs ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 3 تير 1395 ساعت: 15:33

صفحه بندی