Cocoa Memory Management notes for Apple development tutorials

Source: Internet
Author: User

AppleDevelopment tutorialCocoaMemory Management notes are the content to be introduced in this article. The content can be described in two ways. Let's take a look at the details.

The following method is incorrect.

 
 
  1. Instance you don’t own is sent release- (void)reset {NSNumber *zero = [NSNumber numberWithInteger:0]; 

The created autorelease object [self setCount: zero]; [zero release]; // release here is dangerous}

 
 
  1. When you add an object to a collection such as an array, dictionary, or set, the collection takes ownership of 

It. Add an object to the set, and the owner of the object becomes the set.

Code

 
 
  1. //... For (I = 0; I <10; I ++) {NSNumber * convenienceNumber = [NSNumber numberWithInteger: I];
  2. [Array addObject: convenienceNumber];
  3. }
  4. // In this case, releaseNSMutableArray * array; NSUInteger I; is not required;
  5. //... For (I = 0; I <10; I ++) {NSNumber * allocedNumber = [[NSNumber alloc] initWithInteger: I]
  6. ; [Array addObject: allocedNumber]; [allocedNumber release];}
  7. // In this case, we only need to reduce the retain count by 1.

Security return object

The following two methods are correct:

 
 
  1. (NSString *)fullName {    
  2.  NSString *string = [NSString stringWithFormat:@"%@ %@", firstName, lastName];    
  3.  return string;    
  4.  }    
  5.      
  6.  (NSString *)fullName {    
  7.  NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", firstName,    
  8.  lastName] autorelease];    
  9.  return string;    
  10.  }  

On the contrary, the following method is incorrect.

 
 
  1.  (NSString *)fullName {    
  2.  NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", firstName,    
  3.  lastName] release];    
  4.  return string;    
  5. }   

8 Similarly, the following method is also wrong

 
 
  1. (NSString *)fullName {    
  2. NSString *string = [[NSString alloc] initWithFormat:@"%@ %@", firstName,    
  3. lastName];    
  4. return string;    
  5. }   

Object copy Mechanism

There are two copyWithZone methods for implementing the copy protocol:

Use alloc and init ..

Use NSCopyObject.

See the definition of the following object.

 
 
  1. @interface Product : NSObject <NSCopying> 
  2. {  
  3. NSString *productName;  
  4. float price;  
  5. id delegate;  
  6. }  
  7. @end 

The copied memory location map is as follows:

If NSCopying is inherited from supercalass, but the parent class does not implement NSCopying, you must copy the super instance and include the declared variables. Generally, the safe method is to use alloc,
Init..., and set methods

On the other hand, if the super class has implemented NSCopying and you declare some instance variables in your class, you must implement copyWithZone:

If the class does not inherit NSCopying behavior, implement copyWithZone: using alloc, init..., and set methods. The following is an example.

 
 
  1. - (id)copyWithZone:(NSZone *)zone  
  2. {  
  3. Product *copy = [[[self class] allocWithZone: zone]  
  4. initWithProductName:[self productName]  
  5. price:[self price]];  
  6. [copy setDelegate:[self delegate]];  
  7. return copy;  

Some inherit NSCopying behavior classes, but their super class implementation may use NSCopyObject function. NSCopyObject creates an exact shallow copy of an object

By copying instance variable values but not the data they point to. For example, the NSCell class implements copyWithZone in the following way:

 
 
  1. - (id)copyWithZone:(NSZone *)zone  
  2. {  
  3. NSCell *cellCopy = NSCopyObject(self, 0, zone);  
  4. /* Assume that other initialization takes place here. */  
  5. cellCopy->image = nil;  
  6. [cellCopy setImage:[self image]];  
  7. return cellCopy;  

In the above implementation, the shortest copy is used.

To copy objects of variable length, NSMutableCopying must be inherited.

Core Foundation Objects in Cocoa Memory Management

 
 
  1. Core Foundation's memory allocation policy is that you need to release values returned   
  2. by functions with “Copy” or “Create” in their name; you should not release values   
  3. returned by functions that do not have “Copy” or “Create” in their name. 

Examples

 
 
  1. NSString *str = [[NSString alloc] initWithCharacters: ...]; ... [str release];  
  2. is equivalent to  
  3. CFStringRef str = CFStringCreateWithCharacters(...); ...  
  4. CFRelease(str);  
  5. and  
  6. NSString *str = (NSString *)CFStringCreateWithCharacters(...); ...  
  7. [str release];  
  8. and  
  9. NSString *str = (NSString *)CFStringCreateWithCharacters(...);  
  10. ... [str autorelease];  
  11. Memory Management of Nib Objects 

The File's Owner of a nib file defaults to release NIB resources and top-level objects

The global owner of The NIB file is the global application object NSApp. However, when the Cocoa application is terminated, the top-level object in nib does not automatically obtain the dealloc message because the NSApp has been destructed. In other words, even in the nib main file, you have to manage the memory of the top-level object.

In fact, you don't have to worry about it. mac already has two features to help you.

The NSWindow object has an isReleasedWhenClosed attribute. If it is set to YES, the related objects are automatically closed when the window object is closed.

The owner of the nib file is an NSWindowController object. Then, it calls NSDocument to manage an NSWindowController instance and automatically releases

So the reality is that although you are responsible for releasing a top-level object in the nib file, as long as your nib file owner is an NSWindowController instance, it will help you release it. If one of your objects loads nib itself and the file owner is not NSWindowController, you can define outlets for the objects in nib so that you can release them as appropriate. If you do not want to declare outlet for every object, you can also do this:

InstantiateNibWithOwner: topLevelObjects: Method of NSNib class to obtain all top-level objects in the nib file

Memory management can be summarized as follows:

1) You have an object created by using functions with alloc, new, and copy.

2) You can gain ownership through retain

3) any object may have multiple owners.

4) You must release your objects by sending release or autorelease

5) You cannot release objects that are not yours.

6) for the set type assignment function, you can retain the input object, you can also copy a copy, depending on your own requirements.

7) in the function (void) dealloc, you must release your declared instance variable.

8) When the pointer variable is used up, it must be set to nil.

9) Make sure that an object is not released.

10) do not directly call dealloc at any time

Summary:AppleDevelopment tutorialCocoa memoryI hope this article will help you with the introduction of management notes!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.