__weak is awesome

I just read the documentation for __weak and (weak) semantics in objective-c ARC. Pay attention, this is important: __weak and weak properties get set to nil when they no longer point to strongly retained memory locations.

No code formatter so hold onto your hats this is going to look ugly:

-(void)test_weak_prevents_ex_bad_access{
    NSArray * __weak weak_array;

    NSArray *strong_array = [[NSArray alloc] initWithObjects:@"hello", nil];
    weak_array = strong_array;
    strong_array = nil;

    STAssertNoThrow([weak_array count], nil);
}

-(void)test_weak_is_set_to_nil_when_reference_is_deallocd{
    NSArray * __weak weak_array;
    NSArray *strong_array;

    strong_array = [[NSArray alloc] initWithObjects:@"hello", nil];
    weak_array = strong_array;
    strong_array = nil;
    
    STAssertNil(weak_array, nil);
}

Comments