2011年11月18日 星期五

Stanford CS193p Fall 2011 Note-03

strong vs weak

1. strong "keep this in the heap until I don't point to it anymore"
    I won't point to it anymore if I set my pointer to it to nil.
    Or if I myself am removed from the heap because no one strongly points to me!

2. weak "keep this as long as someone else points to it strongly"
    If it gets thrown out of the heap, set my pointer to it to nil automatically
    (if user on iOS 5 only).

3. This is not garbage collection!
     It's way better. It's reference counting done automatically for you.

4. Finding out that you are about to leave the heap
    A special method, dealloc, is called on you when your instance's memory is freed
    from the heap. You will rarely ever have to implement this method. It's  "too late"
    to do much useful here.

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-----------------------------------------------------------------------------

nil

1. The value of an object pointer that does not point to anything
    id obj = nil;
    NSString *hello = nil;

2. Like "zero" for a primitive type (int, double, etc.)
    Actually, it's not "like" zero: it is zero.

3. All instance variables start out set to zero
     Thus, instance variables that are pointers to objects start out with the value of nil.

4. Can be implicitly tested in an if statement
   if (obj) { } // curly braces will execute if obj points to an object
   // i.e. if (obj != nil) { }

5. Sending messages to nil is (mostly) okay. No code gets executed.
   If the method returns a value, it will return zero.
   int i = [obj methodWhichReturnsAnInt]; // i will be zero if obj is nil

6. Be careful if the method returns a C struct. Return value is undefined.
    CGPoint p = [obj getLocation]; // p will have an undefined value if obj is nil

-----------------------------------------------------------------------------

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。