Strong and Weak Confusion in iOS - ios

I am little confused about using Strong or Weak in my particular case.
I have one class ParentClass which has 3 object ContainerClass1, ContainerClass2 and ContainerClass3.
Each ContainerClass has its own strong properties with Mutable objects like NSMutableArray
Now in my case, I have to show only one ContainerClass at a time, so if ContainerClass1 is shown then ContainerClass2 and ContainerClass3 is not required.
So I thought when I show ContainerClass1, will set ContainerClass2 and ContainerClass3 objects to nil. Here I am confused whether just setting the other ContainerClass(not shown) to nil will release its memory? because they have strong properties to other objects.
Or should I need to set all other ContainerClass's strong properties to nil first and then set ContainerClass to nil?
Thanks in advance.

#zoeb, may this link will help you to keep away from basic memory problems.
how-to-overcome-memory-problems-in-iphone-applications-with-automatic-reference-counting
Edited:
As we know that Apple introduced ARC in IOS 5.0, ARC is compiler level feature that simplifies process of lifetime of objective-c objects. Before ARC introduced, We managed memory manually means “Manual Reference Counting(MRC)” . With MRC, Developer need to remember when to release or retain object. Means that Developer need to manage life cycle of objective-c objects.
According to Developer perspective, We are mostly interested to adding new features in our application rather then focusing on memory issues. But the things is sure that memory management perform crucial role in application success. To Provide help to Developer, Apple was figure out the way of automatically manage memory.
ARC is smartly manage memory but this is not 100 percent. We need to focus on some points while development to remove our application from lack of memory problem. Here i will try to provide solution of manage memory in ARC base application. that is not 100 percent as well. but its will try to help compiler to estimate life cycle of objective object.
Here are the some steps that you need to implement in your every controllers.
Step 1. Declare weak property to every UI Controls that used in application.
Example : #property (nonatomic, weak) IBOutlet UIButton* btnPost;
#property (nonatomic, weak) IBOutlet UITableView* tblMessages;
etc.
Step 2. As per our developer most confusing question is that whether compiler allow to declare “dealloc” method in ARC base application. the answer is yes but don’t allowed to declare “[super dealloc]” inside it. so override “dealloc” method in every controllers.
-(void)dealloc{
}
Step 3. Remove heavy loaded object from superview in “dealloc” method rather then setting just “nil” reference like MKMapview, ScrollView etc.
-(void)dealloc{
dictAddress = nil;
arrayList = nil;
[map removeFromSuperview];
[scrollView removeFromSuperview];
}
Step 4. Avoid dead lock mechanism. (Example : Class A and Class B is there. Class B is declared Delegate with property type “Strong”. so that Class A and Class B dependent on each other on one is going to release. so in that case “dealloc” method is not called of either classes. so that class keep in memory. to removed such cases we need to keep “Assign” reference to Delegate object.) this is just for example. We need to consider other things as well like “Keep weak reference for block so it will release objects once its execution completed”.
these are the basic steps that avoiding memory problems. Still if you face memory problems then you need to take help of Analyzer to find leak and memory usage.
Below link will help you to analyze memory.
Mamory analyzer

The confusion between strong and weak will be clear with the below link.
Differences between strong and weak in Objective-C

Related

Manually set nil to swift object to avoid retain cycle?

I've been profiling one of the apps written in swift lately and been very frustrated with ARC in general, coming from languages where mark-and-sweep GC is the norm.
Especially, UIViewControllers that are very complex with lots of dependencies to other class, I've been failing to get ARC working properly. But I know that simply setting retained objects to nil gets them deallocated without dabbling with ARC.
This is especially true for UIViewController where I can set nil to all retained objects in viewDidDisappear or the similar.
Is this kind of practice considered bad / harmful? Should I just try harder to get ARC working?
edit: By not working, I mostly mean to break Strong Reference Cycle, which becomes quite unwieldy when there are multiple hierarchies of dependencies.
edit: FYI, I'm aware that using weak / unowned in declaration / capture list breaks the retain cycle. I'm asking in cases where using those norms become unwieldy due to the complexity of an object or, rather, the retain cycle of an object.
I think you should take a look at your class structure - basically work out which classes should "own" certain properties (i.e. strong reference) and who just needs to be referencing them when they are available (i.e. weak references).
I think it is well worth thinking about this, as it will probably streamline your code. It will also give you an opportunity to really think about privilege - do all these other classes really need access to these objects etc.
The real problem with setting things to nil is that you have to be sure that you are catching all strong reference cycles and that, ultimately, you are not benefiting from ARC making your life easier.
Try deinit Method its wright way I guess
deinit{
person = nil
}

The best route to declare a BOOL as iVar or Property

I have read a few questions on the differences between iVars and Properties like these: Why would you use an ivar?
ios interface iVar vs Property
What I would like to know is... If I am creating a BOOL that needs to be accessed in multiple methods in a UIViewController (for example) what is the best way to create these?
At present I create proprties. This works fine and as expected. But as I read/learn more it appears that creating an iVar would be better for performance.
Like:
#interface ViewController : UIViewController{
BOOL myBool;
}
Would this be better for performance, and can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other - as I can with property approach?
can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other
Of course you can, even if you set the value to NO. It is an instance variable and thus shared between all methods of one instance.
Would this be better for performance
No, unless you access the property very, very often, like 2^20 times per frame. Have a look at this Big Nerd Ranch post about iVar vs property performance. Usually the performance gain is not worth the loss in clarity.
The "better performance" is something that would be very rare to affect an app. Write code for clarity, then if there are performance issues profile and fix the code that is actually causing the problem.
For your purpose an ivar would be equivalent to using a property. Performance-wise the ivar is slightly better because you access it directly, whereas with a property you invoke a method (getter or setter) that was generated by the compiler in the background.
I wouldn't worry about performance, though. Typically the difference will be negligible. Unless you have some really special need, I would always use properties because it usually results in clearer code. It's also a good habit to have getter and setter methods - even if they are generated by the compiler for you - because they encapsulate the data of your class.
I usually go with this:
#interface MyVC : UIViewController
#property (nonatomic, getter=isDoingSomething) BOOL doingSomething;
#end
I also explicitly name the getter in the property declaration which gives you access to the property in a way that is easy to read. (Setting the property is done by sending setDoingSomething: and the getter is [theVC isDoingSomething])
Nonatomic properties are recommended on iOS. In regards to what I had backwards before, the default atomic behavior adds locks to the synthesized code, and is not recommended for performance reasons. Any issues with threads would have to be handled in your own setters (which you would have to do anyway when using an ivar). Personally I haven't ran into any issues with this.
I won't repeat other answers about performance but besides pointing out the fact that tapping a button sends way more messages than accessing a property, so the performance penalty is trivial.

Properties and their backing ivars

Hi imagine I have properties in the .h file:
#property (nonatomic) NSString * myText;
#property (nonatomic) SomeClass * someObj;
Now, in the class implementation.
Say, I didn't forget to use synthesize, and I called:
#synthesize myText, someObj;
Now say in code I forget to put self before the property name (and directly refer to the ivar):
myText = #"Hello";
someObj = [[SomeClass alloc] init];
My question is: is this a problem? What problems can it result in? Or it is no big deal?
ps. Say I am using ARC.
My question is: is this a problem?
This is called "direct ivar access". In some cases, it's not a problem, but a necessity. Initializers, dealloc, and accessors (setters/getters) are where you should be accessing self's ivars directly. In almost every other case, you would favor the accessor.
Directly accessing ivars of instances other than self should be avoided. Easy problem here is that you may read or write at an invalid address (undefined behavior), much like a C struct. When a messaged object is nil, the implementation of that message is not executed.
What problems can it result in?
Biggest two:
You won't get KVO notifications for these changes
And you are typically bypassing the implementation which provides the correct semantics (that can be justified). Semantics in this case may equate to memory management, copying, synchronization, or other consequences of a change of state. If, say, a setter is overridden, then you are bypassing any subclass override of that setter, which may leave the object in an inconsistent state.
See also: Why would you use an ivar?
For clarity, I recommend always using
self.propertyname
as opposed to
propertyname
as this removed any confusion between what variable belong to the class or have been declared locally above in the method.
To enforce this, try to avoid using #synthesize at all, which is only needed if you provide both custom getter and setter (but not one or the other)
The compiler automatically allows you to use _propertyname in the getter/setter (which is necessary to prevent recursive calls of the function)
You should not access the underlying instance variables by accident, only if you plan to do so.
Unexpected side effects may be that KVO doesn't work, overriding accessor methods are not called and the copyand atomic attributes have no effect.
You don't need to use #synthesize since Xcode 4.4, if you use default synthesis the compiler does an equivalent of
#synthesize myText = _myText;
so that
_myText = #"Hello";
self->_myText = #"Hello";
are equivalent and myText = #"Hello"; results in an "undefined identifier" compiler error.
If you use just #synthesize myText the compiler does (for backward compatibility reasons):
#synthesize myText = myText;
which is error prone.
Note that there are valid reasons to use the underlying instance variables instead of the accessor - but it's bad style to do this by accident.
For 30 years now, the recommended practice has been:
use getter/setter methods or the new . operator to read and write ivars.
only access ivars directly when you must.
pick ivar names to prevent accidentally using them, unless the ivar is one that will always be accessed directly (that is why the default behaviour and convention is to prefix ivars with an underscore).
You need to access ivars directly in a few situations:
Manual memory management requires it. You won't need this if ARC is enabled.
If you are going to read the variable variable millions of times in quick succession, and you can't assign it to a temporary variable for some reason.
When you're working with low level C API, it probably needs a pointer to the ivar, Apples libxml2 sample code accesses ivars directly for example.
When you are writing the getter or setter method yourself, instead of using the default #synthesize implementation. I personally do this all the time.
Aside from these situations (and a few others), do not access ivars directly. And prefix all ivars with an underscore, to make sure you don't accidentally access them and to prevent them appearing in xcode's autocomplete/intellisense while you code.
The two main reasons for the convention are:
Getter/setter methods and properties can be kept around when the underlaying memory structure of your class changes. If you rename an ivar, all code that reads the ivar will break, so best to have zero code or almost no code that accesses ivars directly.
Subclasses can override getters and setters. They cannot override ivars. Some people think subclasses shouldn't be allowed to override getters and setters - these people are wrong. Being able to override things is the entire point of creating a subclass.
Fundamental features like KVC and KVO can fall apart if you access ivars directly.
Of course, you can do whatever you want. But the convention has been around for decades now and it works. There is no reason not to follow it.
Contrary to what other answers seem to agree upon, I would recommend to always use direct ivar access unless you are very clear about what you are doing.
My reasoning is simple:
With ARC, it's not even more complicated to use direct property access, just assign a
value to the ivar and ARC takes care of the memory management.
(And this is my main point:) Property accessors may have side-effects.
This is not only true for property accessors you write, but may also be true for
subclasses of the class you are implementing.
Now these accessors defined in subclasses may very well rely on state that the subclass
sets up in it's initializer, which has not executed at this point, so you calling those
accessors might lead to anything from undefined state of your object to your application
throwing exceptions and crashing.
Now, not every class may be designed to be subclassed, but I think it's better to just use one style everywhere instead of being inconsistent depending on the class you are currently writing.
On a side note: I would also recommend to prefix the name of every ivar with an _, as the compiler will do automatically for your properties when you don't #synthesize them.

Creating Objects on the fly in Objective-C

I'd like a critique of the following method I use to create objects:
In the interface file:
MyClass * _anObject;
...
#property (retain, nonatomic) MyClass * anObject;
In the implementation file:
#property anObject = _anObject
so far, so simple. Now let's override the default getter:
(MyClass *) anObject {
if(_anObject == nil) {
self.anObject = [[MyClass alloc] init];
[_anObject dowWhateverInitAction];
}
return _anObject;
}
EDIT:
My original question was about creating the object only (instead of the whole life-cycle), but I'm adding the following so that it doesn't through off anyone:
- (void) dealloc {
self.anObject = nil;
}
/EDIT
The main point of the exercise is that setter is used inside the getter. I've used it for all kind of objects (ViewController, myriad other types, etc.) The advantage I get is:
An object is created only when needed. It makes the app pretty fast
(for example, there are 6-7 views in an app, only one gets created in
the beginning).
I don't have to worry about creating an object before it's used... it happens automatically.
I don't have to worry about where the object will be needed the first time... I can just access the object as if it were already there and if it were not, it just gets created fresh.
Questions:
Does it happen to be an established pattern?
Do you see any drawbacks of doing this?
This pattern is quite commonly used as a lazy-loading technique, whereby the object is only created when first requested.
There could be a drawback to this approach if the object being created lazily takes a fair amount of computation to create, and is requested in a time-critical situation (in which case, it doesn't make sense to use this technique). However I would say that this is a reasonable enough thing to do should the object be quick to create.
The only thing wrong with your implementation (assuming you’re not using ARC yet) is that you’ve got a memory leak—using the setter means that your MyClass instance is getting over-retained. You should either release or autorelease _anObject after that initialization, or assign its value directly instead of calling the setter.
Aside from that, this is totally fine, and it’s a good pattern to follow when the MyClass is an object that isn’t necessarily needed right away and can be recreated easily: your response to memory warnings can include a self.anObject = nil to free up the instance’s memory.
It looks like a decent lazy initialization. Philosophically, one can argue that the drawback is that a getter has a side effect. But the side effect is not visible outside and it is kind of an established pattern.
Lazy instantiation is an established pattern, and it is used by Apple in their (terrible) Core Data templates.
The main drawback is that it is overly complex and often unnecessary. I've lost count of the number of times I've seen this where it would make more sense to simply instantiate the objects when the parent object is initialised.
If a simple solution is just as good, go with the simpler solution. Is there are particular reason why you can't instantiate these objects when the parent object is initialised? Perhaps the child objects take up a lot of memory and are only rarely accessed? Does it take a significant amount of time to create the object and you are initialising your parent object in a time-sensitive section of your application? Then feel free to use lazy instantiation. But for the most part, you should prefer the simpler approach.
It's also not thread-safe.
Regarding your advantages:
An object is created only when needed. It makes the app pretty fast (for example, there are 6-7 views in an app, only one gets created in the beginning).
Are you referring to views or view controllers? Your statement doesn't really make sense with views. I don't normally find myself needing to store view controllers in instance variables/properties at all, I instantiate them when I need to switch to them and push them onto the navigation stack, then pop them off when I'm done.
Have you tried your app without using this pattern? Conjecture about performance is often wrong.
I don't have to worry about creating an object before it's used... it happens automatically.
No, now you have to worry about writing a special getter instead. This is more complex and prone to mistakes than simple instantiation. It also makes your application logic and performance more difficult to understand and reason about.
I don't have to worry about where the object will be needed the first time... I can just access the object as if it were already there and if it were not, it just gets created fresh.
You don't have to worry about that when you instantiate it during your parent object's initialisation.
Yes this is an established pattern. I often use lazy instantiation like this as an alternative to cluttering up -init or -viewDidLoad with a bunch of setup code. I would assign the value to the instance variable instead of using the synthesized setter in the event that this object ends up being created as a result of something happening in -init.

Delegates - retain or assign - release?

I've seen a number of posts related to delegates, and I would like to know the proper way to reference them. Suppose I have an object declared like:
#interface MyViewController : UITableViewController {
id delegate;
}
#property (nonatomic, retain) id delegate;
#end
Through the lifecycle of MyViewController, it will make calls to methods of its delegate in response to interaction with the user.
When it's time to get rid of an instance of MyViewController, does the delegate ivar need to be release'ed in the implementation's dealloc method since it is declared with retain?
Or conversely, should delegate even be retained? Perhaps it should be #property (nonatomic, assign) id delegate? According to Apple's docs:
retain ... You typically use this attribute for scalar types such as NSInteger and CGRect, or (in a reference-counted environment) for objects you don’t own such as delegates.
Normally I'd just go with what the docs say, but I've seen a lot of code that calls retain on a delegate. Is this just "bad code?" I defer to the experts here... What is the proper way to handle this?
You generally want to assign delegates rather than retain them, in order to avoid circular retain counts where object A retains object B and object B retains object A. (You might see this referred to as keeping a "weak reference" to the delegate.) For example, consider the following common pattern:
-(void)someMethod {
self.utilityObject = [[[Bar alloc] init] autorelease];
self.utilityObject.delegate = self;
[self.utilityObject doSomeWork];
}
if the utilityObject and delegate properties are both declared using retain, then self now retains self.utilityObject and self.utilityObject retains self.
See Why are Objective-C delegates usually given the property assign instead of retain? for more on this.
If you assign the delegate rather than retaining it then you don't need to worry about releasing it in dealloc.
It is usually indicative of bad design, since most delegates retain their objects (creating the potential for retain loops and thus leaks.) But there are some cases where an object should retain its delegate. These are usually cases where no reference is available to the object, so the delegate cannot be the one to retain it--but that itself can sometimes indicate bad design.
I've heard a lot of opinions on this as well. I don't know the Right Way, but I can tell you what I've arrived at through my own work.
You want to retain anything that you need to preserve your handle on. That's all ownership is, in a reference-counted environment. It's a declaration that "I'll need this later, don't let it go away on me".
That ALSO means you're responsible for releasing your claim on it. If you don't specifically do that, you're prone to various problems, but especially dealing with delegates which might well retain the object they're a delegate of. If you don't deal with your retention of the delegate, the ownership will be cyclical and the objects will leak. But don't forget to release what you retain, and you'll be okay.

Resources