1

I am new to Objective-C and I would like to ask a question about declaring a local variable (and non-property instance variable) as _weak. Is it a good practice to do so in order to avoid memory leak?

Neli Chakarova
  • 660
  • 1
  • 5
  • 18
  • possible duplicate of [Strong and weak for local variable, I don't understand](http://stackoverflow.com/questions/10922888/strong-and-weak-for-local-variable-i-dont-understand) – Popeye Mar 05 '15 at 12:06
  • If you are new to Obj-C I wouldn't recommend declaring any local variables as weak, unless you need to to use them inside a block, (Xcode will complain and make this obvious) – Alex Mar 05 '15 at 17:17
  • Thanks for the answers. I have already read that thread but I was just wondering if it is something common to write local variables with _weak. – Neli Chakarova Mar 06 '15 at 17:06

1 Answers1

0

Memory leak or problems can occur if you use strong references inside blocks for example. It is better to search on SO before post questions. You should also read here a very nice explain: Differences between strong and weak in Objective-C

If you want to access self method, for example, inside a block, you can define as:

   __block id WeakSelf = self;

then inside your block you can call as:

   {  // -> inside block
   [WeakSelf dosomeFunction];
   } // <-  block ends
Community
  • 1
  • 1
ares777
  • 3,590
  • 1
  • 22
  • 23
  • the memory leaks are not localized only for blocks, there are many other ways of how an application can define a strong reference cycle. – holex Mar 05 '15 at 12:15
  • I know, I just give user an example. – ares777 Mar 05 '15 at 12:22
  • Thanks for the answers. I have already read that thread but I was just wondering if it is something common to write local variables with _weak. – Neli Chakarova Mar 06 '15 at 17:06