티스토리 뷰
Item 29: Understand Reference Counting
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *number = [[NSNumber alloc] initWithInt:1337];
[array addObject:number];
[number release];
// do something with 'array'
[array release];
As explained previously, this code won’t compile under ARC, owing to the explicit calls to release. In Objective-C, a call to alloc will result in the return of an object that is said to be owned by the caller. That is to say, the caller’s interest has already been registered because it used alloc. However, it is important to note that this does not necessarily mean that the retain count is exactly 1. It might be more, since the implementation of either alloc or initWithInt: may mean that other retains have been made on the object. What is guaranteed, though, is that the retain count is at least 1. You should always think about retain counts in this way. You should never guarantee what a retain count is, only what effect your actions have had on the retain count: whether that is incremented or decremented.
The number object is then added to the array. In doing this, the array also registers its interest by calling retain on the number object within the addObject: method. At this point, the retain count is at least 2. Then, the number object is no longer required by this code, so it is released. Its retain count is now back down to at least 1. At this point, the number variable can no longer be safely used. The call to release means that the object pointed to is no longer guaranteed to be alive. Of course, the code in this scenario makes it obvious that it will be alive after the call to release, since the array is also still referencing it.
To mitigate accidentally using an object that is no longer valid, you will often see a release followed by nilling out the pointer. This ensures that nothing can access a pointer to a potentially invalid object, often referred to as a dangling pointer. For example, it can be done like this:
NSNumber *number = [[NSNumber alloc] initWithInt:1337];
[array addObject:number];
[number release];
number = nil;
An autorelease is used to indicate that the object should be released sometime later but guaranteed to be long enough in the future that the returned value can be retained by the caller if it needs to hold onto it. In other words, the object is guaranteed to be alive across the method call boundary. In fact, the release will happen when the outermost autorelease pool is drained, which, unless you have your own autorelease pools, will be next time around the current thread’s event loop. Applying this to the stringValue method gives the following:
- (NSString*)stringValue {
NSString *str = [[NSString alloc]
initWithFormat:@"I am this: %@", self];
return [str autorelease];
}
Item 30: Use ARC to Make Reference Counting Easier
A __weak local variable can be used to break the retain cycle:
NSURL *url = [NSURL URLWithString:@"http://www.example.com/"];
EOCNetworkFetcher *fetcher =
[[EOCNetworkFetcher alloc] initWithURL:url];
EOCNetworkFetcher * __weak weakFetcher = fetcher;
[fetcher startWithCompletion:^(BOOL success){
NSLog(@"Finished fetching from %@", weakFetcher.url);
}];
ARC handles only Objective-C objects. In particular, this means that CoreFoundation objects are not handled, and the appropriate CFRetain/CFRelease calls must be applied.
Item 31: Release References and Clean Up Observation State Only in dealloc
Item 32: Beware of Memory Management with Exception-Safe Code
Item 33: Use Weak References to Avoid Retain Cycles
When the reference to the instance of EOCClassA is removed, the property unsafe_unretained still points to the instance that is now deallocated. With the weak property, the property points to nil.
The general rule is that if you don’t own an object, you should not retain it.
Item 34: Use Autorelease Pool Blocks to Reduce High-Memory Waterline
Item 35, 36은 deprecated 등의 이유로 안 읽고 넘어감
https://www.oreilly.com/library/view/effective-objective-c-20/9780133386950/
이 책으로 공부 중이고, 기억하면 좋을 것 같은 부분을 발췌 + 공부 + 정리합니다.
'Objective-C 2.0' 카테고리의 다른 글
7. The System Frameworks (0) | 2023.01.03 |
---|---|
6. Blocks and Grand Central Dispatch (0) | 2022.12.29 |
4. Protocols and Categories (0) | 2022.03.04 |
3. Interface and API Design (0) | 2022.01.25 |
2. Objects, Messaging, and the Runtime (0) | 2022.01.19 |
- Total
- Today
- Yesterday
- 어댑터
- 터치리스너
- objc
- 알림대화상자
- 액션바
- 인플레이터
- 쉐이프드로어블
- prepareforreuse
- 스낵바설정
- 프래그먼트
- 전화연결하기
- allcases
- 안드로이드
- 데이터
- subscript
- 카카오톡열기
- 부가데이터
- 뷰페이저
- 프래그먼트매니저
- 상태드로어블
- 제스처디텍터
- CaseIterable
- 다이얼연결
- 비트맵버튼
- Objective-C
- 전화걸기연결
- 표현패턴
- 페이저타이틀스트립
- swift
- ios
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |