您好,登錄后才能下訂單哦!
該教程是討論IOS平臺上內存管理規則之外的一些特殊情況,我相信大部分的開發人員可能都沒有覺察到。
我們先普及一下Objectivie-C中的內存管理的基本知識,如果你已經比較熟悉了,可以直接跳過該節。Objective-C使用的是引用計數(Reference Counting),引用計數就是對象用一個變量來保存有幾個地方(類、方法等)在使用它。當一個對象被創造出來時,它的引用計數(下面我們用retainCount來表示這個值)為1,在應用程序運行的過程中,可能有很多地方都用到了這個對象,凡是用到這個對象時,就將它的retainCount加1,當不用了時,再將其retainCount減1,當對象的retainCount為0時,表示沒有人在用這個對象了,系統就會釋放這個對象所占用的內存。
- NSString *emptyStr = [NSString new];
- NSLog(@"emptyStr retainCount: %u", emptyStr.retainCount);
- NSString *emptyStr1 = [NSString new];
- NSString *emptyStr2 = [NSString new];
- NSLog(@"emptyStr1 address: %p", emptyStr1);
- NSLog(@"emptyStr2 address: %p", emptyStr2);
- NSLog(@"emptyStr1 retainCount: %u", emptyStr1.retainCount);
- NSLog(@"emptyStr2 retainCount: %u", emptyStr2.retainCount);
- NSString *nonEmptyStr1 = @"Hello";
- NSString *nonEmptyStr2 = [[NSString alloc] initWithString:@"Hello"];
- NSString *nonEmptyStr3 = [[NSString alloc] initWithFormat:@"%@", @"Hello"];
- NSLog(@"nonEmptyStr1 address: %p", nonEmptyStr1);
- NSLog(@"nonEmptyStr2 address: %p", nonEmptyStr2);
- NSLog(@"nonEmptyStr3 address: %p", nonEmptyStr3);
- NSLog(@"nonEmptyStr1 retainCount: %u", nonEmptyStr1.retainCount);
- NSLog(@"nonEmptyStr2 retainCount: %u", nonEmptyStr2.retainCount);
- NSLog(@"nonEmptyStr3 retainCount: %u", nonEmptyStr3.retainCount);
- NSArray *emptyArray1 = [[NSArray alloc] init];
- NSArray *emptyArray2 = [[NSArray alloc] init];
- NSArray *emptyArray3 = [[NSArray alloc] initWithArray:emptyArray1];
- NSLog(@"emptyArray1 address: %p", emptyArray1);
- NSLog(@"emptyArray2 address: %p", emptyArray2);
- NSLog(@"emptyArray3 address: %p", emptyArray3);
- NSLog(@"emptyArray1 retainCount: %d", emptyArray1.retainCount);
- NSLog(@"emptyArray2 retainCount: %d", emptyArray2.retainCount);
- NSLog(@"emptyArray3 retainCount: %d", emptyArray3.retainCount);
- NSArray *nonEmptyArray1 = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
- NSArray *nonEmptyArray2 = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
- NSLog(@"nonEmptyArray1 address: %p", nonEmptyArray1);
- NSLog(@"nonEmptyArray2 address: %p", nonEmptyArray2);
- NSLog(@"nonEmptyArray1 retainCount: %d", nonEmptyArray1.retainCount);
- NSLog(@"nonEmptyArray2 retainCount: %d", nonEmptyArray2.retainCount);
- NSDictionary *emptyDict1 = [[NSDictionary alloc] init];
- NSDictionary *emptyDict2 = [[NSDictionary alloc] init];
- NSLog(@"emptyDict1 address: %p", emptyDict1);
- NSLog(@"emptyDict2 address: %p", emptyDict2);
- NSLog(@"emptyDict1 retainCount: %d", emptyDict1.retainCount);
- NSLog(@"emptyDict2 retainCount: %d", emptyDict2.retainCount);
- NSString *s1 = [NSString new];
- NSString *s2 = [NSString alloc] initWithString:@"Hello"];
- NSArray *a = [NSArray alloc] init];
- NSDictionary *dict = [NSDictionary alloc] init];
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。