티스토리 뷰

Objective-C 2.0

5. Memory Management

varyeun 2022. 5. 10. 16:15

Item 29: Understand Reference Counting

 

An object’s retain count incrementing and decrementing as it goes through its life cycle

 

An object graph showing an object eventually being deallocated after all references to it are released

 

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

 

Difference between  unsafe_unretained  and  weak  attributes when the object pointed to by the property is deallocated

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/

 

Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS and OS X Programs

Write Truly Great iOS and OS X Code with Objective-C 2.0! Effective Objective-C 2.0 will help you harness all of Objective-C’s expressive power to write OS X or iOS code … - Selection from Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS

www.oreilly.com

 

이 책으로 공부 중이고, 기억하면 좋을 것 같은 부분을 발췌 + 공부 + 정리합니다.

'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
댓글