tailieunhanh - Learn Objective C on the Mac phần 6

Quản lý bộ nhớ là một vấn đề khó khăn. Ca cao của giải pháp là khá thanh lịch nhưng không mất một thời gian để tâm trí bạn. Ngay cả những lập trình viên với nhiều thập kỷ kinh nghiệm có vấn đề khi lần đầu tiên gặp phải tài liệu này, do đó, không lo lắng nếu nó rời khỏi đầu của bạn quay một thời gian. | 162 CHAPTER 9 Memory Management NOTE__ Memory management is a hard problem. Cocoa s solution is rather elegant but does take some time to wrap your mind around. Even programmers with decades of experience have problems when first encountering this material so don t worry if it leaves your head spinning for awhile. If you know that your programs will only be run on Leopard or later you can take advantage of Objective-C s garbage collection which we ll discuss at the end of this chapter. We won t feel sad if you skip to the end really. If you want to run on older versions of Mac OS X or you re doing iPhone development you will want to read the whole chapter. Object Life Cycle Just like the birds and the bees out here in the real world objects inside a program have a life cycle. They re born via an alloc or a new they live receive messages and do stuff make friends via composition and arguments to methods and eventually die get freed when their lives are over. When that happens their raw materials memory are recycled and used for the next generation. Reference Counting Now it s pretty obvious when an object is born and we ve talked a lot about how to use an object but how do we know when an object s useful life is over Cocoa uses a technique known as reference counting also sometimes called retain counting. Every object has an integer associated with it known as its reference count or retain count. When some chunk of code is interested in an object the code increases the object s retain count saying I am interested in this object When that code is done with the object it decreases the retain count indicating that it has lost interest in that object. When the retain count goes to 0 nobody cares about the object anymore poor object so it is destroyed and its memory is returned to the system for reuse. When an object is created via alloc or new or via a copy message which makes a copy of the .

TỪ KHÓA LIÊN QUAN