ios programming (3rd) notes

Ownership

  • When an object  has an instance variable that  points to another object , the object  with the pointer is said to own the object  being pointed to.
  • When a method(function) has a local variable that points to an object, that method is said to own the object being pointed to.

Recall that a collection object, like an NSMutableArray, holds pointers to objects instead of acutally containing them. These pointers convey ownership: an array owns the objects it points to.

Because objects own other objects, which can own other objects, the destruction of a single object can set off a chain reaction of loss of ownership, object destruction, and freeing up of memory.

Let's add some code so that we can see this destruction as it happens.

NSObject implements a dealloc method, which is sent to an object when it is about to be destroyed. We can override this method to print something to the console when an object is destoryed.

- (void) dealloc
{
    NSLog(@"Destroyed: %@", self);
}

A variable can also be declared using the __unsafe_unretained attribute. Like a weak reference, an unsafe unretained reference does not take ownership of the object it points to. Unlike a weak reference, an unsafe unretained reference is not automatically set to nil when the object it points to is destroyed. This makes unsafe unretained variables, well, unsafe. __unsafe_unretained exists primarily for backwards compatibility. 

Be safe. Change this variable back to __weak.

__weak BNRItem * container;

property default attributes:

atomatic,readwrite,and assign

so we normally declare property like this

@property (nonatomic) BNRItem* pd;

a sample

//object 
@property (nonatomic, strong) BNRItem *containedItem;
@property (nonatomic, weak) BNRItem *container;
@property (nonatomic, strong) NSString *itemName;
@property (nonatomic, strong) NSString *serialNumber;
//primitive assign
@property (nonatomic) int valueInDollars;
@property (nonatomic, readonly, strong) NSDate *dateCreated;

copy

@property (nonatomic, copy) NSString *itemName;

denotes

- (void) setItemName:(NSString * ) str
{
    itemName = [str copy];
}

 

 

 

 

posted on 2012-07-13 09:17  grep  阅读(284)  评论(0编辑  收藏  举报