- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 151字
- 2021-07-02 14:45:04
Memory leaks
This issue is probably the most common in Objective-C and Swift. A memory leak occurs when an allocated object is not referenced anymore, but still has a retain count greater than 0. In Objective-C, those are very easy to write, as follows:
- (void) doSomething {
NSString *string = [[NSString alloc] init];
// do something with the string
[string retain];
// Do more things with the string
[string release];
}
Unlike the previous example, there's an additional call to retain, and this call will increment the retain count effectively. Every alloc and retain call should be balanced by release, and we failed to do so in the example. You now have a leak in your program. There are many ways to generate leaks in Swift, and in later sections of this book, we'll cover chapter how they can appear, how to debug them, and how to fix them.