-1

1) Wikipedia said: "The difference between weak (_weak) and assign (_assign) is that when the object the variable pointed to is being deallocated, whether the value of the variable is going to be changed or not. weak ones will be updated to nil and the assign one will be left unchanged, as a dangling pointer."

But after I tried a sample in Xcode like this

__weak NSObject *obj1 = [[NSObject alloc] init];
[obj1 release];

If Wiki's right, the address obj1 pointed to must be nill after release. But the address obj1 pointed to is still 0xabcdef... Wiki's wrong ?

2) Help me distinguish __weak, __block, __assign ?

DungLe
  • 265
  • 1
  • 3
  • 10
  • 1
    There is no such thing as `__assign`. You can define properties with the `assign` attribute but there is no `__assign` keyword like there is with `__weak`. And `__block` has nothing at all to do with the main part of your question. – rmaddy Jun 30 '13 at 02:19
  • So Wiki's right or wrong ??? – DungLe Jun 30 '13 at 02:21
  • I read that topic but I still don't understand about __weak, __block – DungLe Jun 30 '13 at 02:22
  • 1
    The Wikipedia article is correct. But understand that the variable may not be set to `nil` instantly. There are cases where it isn't set to `nil` until a little later. Some of this may depend on optimization levels. – rmaddy Jun 30 '13 at 02:50

1 Answers1

2

The __weak attribute for "Zeroing weak references" is only available with ARC (Automatic Reference Counting).

Your code is obviously compiled with MRC (Manual Reference Counting). In that case, the __weak attribute is just ignored and you should get a compiler warning

__weak attribute cannot be specified on an automatic variable when ARC is not enabled [-Wignored-attributes]

Therefore, releasing the object has no effect on the obj1 variable itself. It is a dangling pointer, pointing to a deallocated instance.


If you convert your code to ARC then you have to remove the release statement. Now you will get a different warning

assigning retained object to weak variable; object will be released after assignment [-Warc-unsafe-retained-assign]

The object will be deallocated and obj1 set to nil immediately, because there are no strong references to the object after the assignment.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382