Do I need getters and setters if i'm depending on garbage collection in objective-c - objective-c

New to Cocoa and Objective-c.
Do I need getters and setters if I'm depending on garbage collection?
For example is it safe to just modify instance variables directly without the dot syntax?
And in the dealloc method can I sent them to nil instead of release (or do I even have to release them)?

Property (Getters and setters) is a mean of encapsulation, and ivar is an implementation detail.
Accessing via properties allow you to change the internal design while keeping the interface unchanged.
Whether the program has GC enabled or not, you shouldn't access ivar directly externally (internally is fine).
(Also, the -dealloc method is ignored if GC (not ARC) is enabled. You could implement -finalize. But the GC should be smart enough to clean the no-longer-needed ivars, whether to set them to nil or not.)

From within the class itself you can directly modify the private variables of course. Think about accessors mainly to expose a public interface and avoid other classes to modify directly your object. This comes from the Object Oriented Paradigm and not with the memory management.
About the release it is better to understand clearly how it works using the retain count and what have a role on that count. Some method like init increase retains the object and some other do not. A lot static methods that return new ready to use object like imageWithNamed: return an autorelease object that you have to retain explicitly to own them.
The best is to release and set to nil when you have transfer the ownership to another object (ex. an array)
ex.
NSString *myName = #"zgueb";
NSArray *myFamily = [[NSArray alloc] initWithObjects:myName, nil];
// now myName is retained by myFamily, i can release it
[myName release];
myName = nil;
Is it clear.
Vince.

Related

Conflict between memory management descriptions in ObjC book and official docs

I'm trying to learn/understand what happens and why when working with or creating various objects. (Hopefully to LEARN from the docs.)
I'm reading "Programming in Objective-C 2.0" (2nd edition, by Steven Kochan). On page 408, in the first paragraph is a discussion of retain counts:
Note that its reference count then goes to 2. The addObject: method does this automatically; if you check your documentation for the addObject: method, you will see this fact described there.
So I read the addObject: docs:
Inserts a given object at the end of the array.
There, the description is missing, while other items, like arrayByAddingObject:, state it:
Returns a new array that is a copy of the receiving array with a given object added to the end.
Where in the reference does it indicate that addObject: increases the retain count? Given the presence of ARC, I should still understand what these methods are doing to avoid bugs and issues. What does ARC bring to this? (Going to read that again...)
Great question, I'm glad to see someone actually reading the docs and trying to understand them!
Since you are looking for how to research answers using Apple's documentation more so than the actual answer itself, here is how I found the answer:
First I look at the class reference for addObject: which is a method of NSMutableArray and there is no mention of memory management.
Then I look at the Overview section at the top... Hmmm, still no luck.
Since the behavior might be inherited from a parent class, I look at the Inherits from section at the top of the class reference and see that NSArray is the most immediate parent. Let's check there:
Under the Overview There is one small section about retain's:
Special Considerations
In most cases your custom NSArray class should conform to Cocoa’s
object-ownership conventions. Thus you must send retain to each object
that you add to your collection and release to each object that you
remove from the collection. Of course, if the reason for subclassing
NSArray is to implement object-retention behavior different from the
norm (for example, a non-retaining array), then you can ignore this
requirement.
Okay, I'm still not happy... Where next? The parent class of NSArray is NSObject and I know that it won't be covered there in this case (from experience) so I won't bother checking that. (If the parent was another class or something that might be covered by NSObject, I would keep moving up the tree until I found something.)
The Companion Guides usually contains a lot of good information for these types of classes. Let's try the first one, Collections Programming Topics.
The first section (after Overview) is Accessing Indexes and Easily Enumerating Elements: Arrays. Sounds promising! Click on Relevant Chapters: “Arrays: Ordered Collections”
There it is under Array Fundamentals along with a link to even more information:
And when you add an object to an NSMutableArray object, the object
isn’t copied, (unless you pass YES as the argument to
initWithArray:copyItems:). Rather, an object is added directly to an
array. In a managed memory environment, an object receives a retain
message when it’s added; in a garbage collected environment, it is
strongly referenced. When an array is deallocated in a managed memory
environment, each element is sent a release message. For more
information on copying and memory management, see “Copying
Collections.”
The book must be referring to out of date documentation because you are correct it doesn't mention anything about the retain count. It does in fact retain the object though. The way you need to think of it is not in terms of retain counts (which are useless) but rather ownership. Especially so when using ARC.
When you add an object to an NSMutableArray, it is taking ownership of that object (in ARC terminology it has a strong reference to it).
"What does ARC bring to this?"
ARC does nothing different. All ARC does (besides some optimization) is add the same release, retain, and autorelease statements that you would add yourself without using ARC. All you need to care about is that once you add an object to the array, it will live at least as long as the array.
And the arrayByAddingObject: method creates a new NSArray (or NSMutableArray) containing the object you're passing, and keeps a strong reference to the passed object. The actual array object that it creates has no references yet unless you assign it to either an ivar, property, or local variable. What you assign it to determines it's lifespan.
Basically even without ARC, it's best to think of object life-cycles in terms of ownership, ARC just formalizes that. So because of that, when using the frameworks, it doesn't matter when retains happen or don't happen, you are only responsible for your objects until you pass ownership to another object and you can trust that the framework will keep the object alive as long as it needs it.
Now of course you have to intuit what constitutes ownership. For instance delegate properties are often assign, or in ARC unsafe_unretained or weak, to prevent circular retains cycles (where two objects each retain each other), though are sometimes retained/strong so you need to look into those on a case by case basis.
And also in cases like key value observing and NSNotification observing the object you are observing does not retain the observer.
But those are really exceptions to the rule. Generally you can assume a strong reference.
Regarding this sentence above: "The actual array object that it creates has no references yet unless you assign it to either an ivar, property, or local variable. What you assign it to determines it's lifespan." I'll try to explain:
When you run this piece of code: [someArray arrayByAddingObject:someObject]; you've instantiated a new NSArray or NSMutableArray object (depending on which object type someArray is) but you haven't actually assigned it to any reference. That means that if you're using ARC, it may be immediately released afterwards, or if not using ARC, it will be released when it's autoreleasepool is drained (probably on the next iteration of that thread's runloop).
Now if instead you did this: NSArray *someOtherArray = [someArray arrayByAddingObject:someObject]; you now have a reference to the newly created array, called someOtherArray. In this case, this is a local variable who's scope is only within whichever set of { } it resides (so it could be inside an if statement, a loop, or a method. Now if you do nothing else with it, it will die sometime after it's scope ends (it isn't guaranteed to die right away, but that isn't important, you just can't assume it lives longer).
Now if in your class you have an iVar (instance variable) declared in the header like NSArray *someOtherArray; (which is strong by default in ARC) and you run someOtherArray = [someArray arrayByAddingObject:someObject]; somewhere in your class, the object will live until you either remove the reference (someOtherArray = nil), you overwrite the reference (someOtherArray = someThirdArray), or the class is deallocated. If you were not using ARC, you would have to make sure to retain that to achieve the same effect (someOtherArray = [[someArray arrayByAddingObject:someObject] retain]; which is essentially what ARC is doing behind the scenes).
Or you may have a property declared instead like #property (nonatomic, strong) NSArray *someOtherArray in which self.someOtherArray = [someArray arrayByAddingObject:someObject]; would achieve the same effect but would use the proprety accessor (setSomeOtherArray:) or you could still use someOtherArray = [someArray arrayByAddingObject:someObject]; to set the iVar directly (assuming you #synthesized it).
Or assuming non-ARC, you might have declared the property like #property (nonatomic, retain) NSArray *someOtherArray in which self.someOtherArray = [someArray arrayByAddingObject:someObject]; would behave exactly as ARC would, but when setting the iVar directly you would still need to add that retain manually.
I hope that clears things up a bit, please let me know if there's anything I glossed over or left out.
As you mentioned in your comment, the key here is intuitively knowing when an object would be considered owned by another one or not. Luckily, the Cocoa frameworks follow a pretty strict set of conventions that allow you to make safe assumptions:
When setting an NSString property of a framework object (say the text property of a UILabel for example) it is always copied (if anyone knows of a counter-example, please comment or edit). So you don't have to worry about your string once you pass it. Strings are copied to prevent a mutable string from being changed after it's passed.
When setting any other property other than delegate, it's (almost?) always retained (or strong reference in ARC)
When setting delegate properties, it's (almost?) always an assign (or weak reference) to prevent circular retain cycles. (For instance, object a has a property b that is strong referenced and b has a strong referenced delegate property. You set a as the delegate for b. Now a and b are both strongly referencing each other, and neither object will ever reach a retain count of 0 and will never reach it's dealloc method to dealloc the other object. NSURLConnection is a counter-example that does strongly reference it's delegate, because it's delegate is set via a method -- see that convention below -- and it's convention to nil out or release an NSURLConnection after it completes rather than in dealloc, which will remove the circular retain)
When adding to an array or dictionary, it's always retained (or strong reference).
When calling a method and passing block(s), they are always copied to move them from the stack (where they are initially created for performance purposes) into the heap.
Methods that take in object parameters and don't return a result immediately are (always? I can't think of any that don't) either copying or retaining (strong referencing) the parameters that you pass to ensure that the method can do what it needs to with them. For instance, NSURLConnection even retains it's delegate because it's passed in via a method, whereas when setting the delegate property of other objects will not retain, as that is the convention.
It's suggested that you follow these same conventions in your own classes as well for consistency.
Also, don't forget that the headers of all classes are available to you, so you can easily see whether a property is retain or assign (or strong or weak). You can't check what methods do with their parameters, but there's no need because of the convention that parameters are owned by the receiver.
In general, you should look in the "most global" spot for information about anything in the Cocoa APIs. Since memory management is pervasive across the system APIs and the APIs are consistent in their implementation of the Cocoa memory management policy, you simply need to read and understand the Cocoa memory management guide.
Once understood, you can safely assume that all system APIs implement to that memory management policy unless explicitly documented otherwise.
Thus, for NSMutableArray's addObject: method, it would have to retain the object added to the array or else it would be in violation of that standard policy.
You'll see this throughout the documentation. This prevents every method's documentation from being a page or more long and it makes it obvious when the rare method or class implements something that is, for whatever reason (sometimes not so good), an exception to the rule.
In the "Basic Memory Management Rules" section of the memory management guide:
You can take ownership of an object using retain.
A received object is normally guaranteed to remain valid within the
method it was received in, and that method may also safely return the
object to its invoker. You use retain in two situations: (1) In the
implementation of an accessor method or an init method, to take
ownership of an object you want to store as a property value; and (2)
To prevent an object from being invalidated as a side-effect of some
other operation (as explained in “Avoid Causing Deallocation of
Objects You’re Using”).
(2) is the key; an NS{Mutable}Array must retain any added object(s) exactly because it needs to prevent the added object(s) from being invalidated due to some side-effect. To not do so would be divergent from the above rule and, thus, would be explicitly documented.

Is it better practice to make member vars retained versus assign

I have member variables in my custom UIViewController that are defined as 'assign' (not 'retain') like this:
#property (nonatomic, assign) UIButton* mSkipButton;
In my loadView method, I set the var, for instance self.mSkipButton, to an autoreleased alloc of the variable type. I then attach it to my controller's view essentially having the view reference count and release it as needed.
This concerns me, however, that I have the pointer stored in my member var and that it could be referencing released memory if the count decrements at some point. Is it better practice to instead declare the variable as 'retain' and then in the viewDidUnload method release the member var (or just set it to nil to release and make sure i don't have an address in there)?
Alternatively, could I simply set the member var to nil in viewDidUnload and not make it a retained variable?
Is it better practice to instead declare the variable as 'retain' and then in the viewDidUnload...?
Yes, use retain -- good instinct. In viewDidUnload, you'd typically just set it to nil via the ivar's setter: self.ivar = nil;
I find it easier to be aware of and manage object codependencies explicitly, than to deal with issues related to using assign. You can completely avoid the issues of holding an unmanaged reference.
Arguments can be made that assign would usually be fine here (and it is in some cases), but using assign can complicate object graphs and ownership for anyone working with the class. As program complexity grows (and the libraries you depend on change), it becomes increasingly difficult to track lifetimes of unmanaged references. Things tend to break, or operate differently on different hardware and software combinations. Attempting to manage the lifetime of an unmanaged object over a complex program or in a concurrent context is self abuse. Guaranteeing defined and predictable behavior/operation reduces bug counts.
That's a property, not a "member var" (known in Objective-C as an instance variable or ivar.)
The semantics of a property depend on how that property is going to be used. Generally speaking, you'll want your properties to be retained for the lifetime of your object. If the property is a connected IBOutlet, this will be done for you by the NIB loader; otherwise, you must be explicit and use the retain or copy attribute on the property.
For objects that are expected to own your object, a property should always be marked assign to avoid a retain loop. For example, an object usually owns any object for which it acts as a delegate (usually, but not always--every CS rule has an exception.)

Objective C - Memory management question?

I know that when i have a property for an object which is set to retain or copy i must do the following.
Object *o = [[Object alloc] init];
self.myObject = o;
[o release];
but what if i don't define a property for myObject?
Can i do the following without having a leak?
Is it better to define a property for every variable I have in every class? Why??
myObject = [[Object alloc] init];
Yes, you can set an instance variable that way and it's totally fine — in fact, that's the preferred way to do it in init methods (because setters might have side effects). Just remember to release the old object (if any) in the variable before setting a new one or you'll leak. And whether you use properties or set the ivar directly, you need to release the object in dealloc.
What you can do is ensure you release the previously allocated object before assigning the variable holding it to a new instance (be it a retained version of another object, or a copy of it).
If you don't define a property for it, don't use the dot syntax.
Because Jacob already answered the part of without property. I will answer the left
Can i do the following without having a leak?
myObject = [[Object alloc] init];
You have to release the myObject somewhere, maybe in the delegate method, or maybe after you finish using it, but remember to release the object, especially before you lose the object reference
Is it better to define a property for every variable I have in every class? Why??
It depends on your coding convention, define all properties will help you with memory management a lot, but it comes with burden and sometimes your team doesn't want to define instance variable, property and synthesize for every variable, which means quite a lot of codes. So, discussing with your team to see what is your weakness and strength. If you are weak at memory management, I recommend to define for every
You don't need to have any properties. Obj-C didn't even have them at all until a couple of years ago with Obj-C 2. Properties are a convenience - they give you some memory management without you writing boilerplate code (the access methods are synthesized for you), and you can use dot notation, which some people are more familiar with than the usual Obj-C syntax.
Having said that properties take care of memory management for you, that's only partially true. You still need to set all properties to nil in your dealloc method. So that really doesn't buy you much, since without properties you'd still need to release each object in dealloc.
The big benefit is that properties handle reference counting for you when assigning objects from one place to another. You don't have to write the getters and setters manually. For this reason, I like properties. Plus, clang is gaining the ability to have properties where you only need the #property line, no need for a backing variable, and no need for an #synthesize line. One-line properties are a win in my book. (OK, two lines, you need to add a line to dealloc too :)

Objective-C Memory Management: When do I [release]?

I am still new to this Memory Management stuff (Garbage Collector took care of everything in Java), but as far as I understand if you allocate memory for an object then you have to release that memory back to the computer as soon as you are finished with your object.
myObject = [Object alloc];
and
[myObject release];
Right now I just have 3 parts in my Objective-C .m file: #Interface, #Implementation and main. I released my object at the end of the program next to these guys:
[pool drain];
return 0;
But what if this program were to be a lot more complicated, would it be okay to release myObject at the end of the program?
I guess a better question would be when do I release an object's allocated memory? How do I know where to place [myObject release];?
This is probably a little over-simplified, but in general, you are going to want to release it where you declared it.
If you declare an object INSIDE a particular method call, then by definition, you will be done with that object (or at least that handle to that object) at the end of that method call... release it then.
If you declare an object as an instance variable, then by definition you will be done with it when that instance is destroyed... release it in the dealloc method of that class.
Keep in mind that "release" does not equal "destroy." When passing objects around in your application, it may make sense to have more than one handle to that object stored in different places... in that case "release" means "I'm done with this object, but someone else may still be using it." Deallocation only occurs when the number of "handles" (retain count) reaches zero.
Apple has some fantastic documentation on memory management, I would check it out at developer.apple.com.
You essentially have three kinds of objects, each with a different pattern.
Transients Objects
In general, you should autorelease transient objects. These are objects that are allocated locally and do not need to exist beyond the method in which they are called. Or they are passed around from method to method.
Chain of Ownership
When one object exists as an instance field inside another, you should release the "owned" (or "child") object when the "owner" (or "parent") object goes out of existence. This is done in the dealloc method of the parent object:
- (void) dealloc {
[child release]; // child was declared as an instance variable
[super dealloc];
}
Lifetime of the Program
When an object is intended to exist for the lifetime of the program, it usually isn't necessary to call release at all, unless some kind of resource cleanup needs to occur. You can put this in applicationWillTerminate:, which you can look up in Apple's documentation.
(You should probably avoid having such objects, but that is a discussion for another question.)
You have to think in terms of ownership. When you take ownership of an object by calling alloc, new or retain, you're also responsible for releasing it, either by calling autorelease when you return an owned object to the caller, or by calling release.
A general rule is:
Local variable: release it within the same method. When you want to return it to the caller, use autorelease
Class member: release it in the dealloc method

Object retain behavior of Objective-C class methods

What's the best practice for retaining and releasing objects passed to class methods?
For instance, if you have a "class variable" declared like so:
static NSString *_myString = nil
...is the right thing to do this:
+ (void)myClassMethod:(NSString *)param {
_myString = param;
}
... which has the drawback that the caller needs to maintain a nonzero retain count on param lest it be released prematurely. Alternatively one could do this:
+ (void)myClassMethod:(NSString *)param {
[_myString autorelease];
_myString = [param retain];
}
...which has the drawback that without a corresponding class-level dealloc call it will leak memory. Or should this sort of class variable chicanery be avoided completely, perhaps with a singleton class that manages the lifetime of these sorts of objects in a more conventional way?
Here are Apple's docs on creating a singleton instance.
The code that I'm working with is the very slick (but still new) Objective Resource project (http://www.iphoneonrails.com/).
Retain and release, absolutely. It's not a leak because the only time when a class's dealloc would be called is when the program ends — at which time the memory will be freed anyway. Doing it the first way would be more hassle and goes against the Cocoa memory-management guidelines.
As for whether it should be a class method or a singleton: Classes themselves generally should not have a lot of independent functionality. They just weren't designed that way in Objective-C, as you can see from the lack of class variables. Class methods should generally deal with creating and managing instances, and sometimes storing shared properties or defaults for all instances. The actual functionality of a class should go into instances. That's the convention in Objective-C.
(Of course, there is no Objective-C God and you're free to ignore conventions, but that's the general wisdom.)
Also, in the case of NSString or any class that has mutable variants (like NSArray or NSDictionary), I'd strongly recommend copying the parameter instead of retaining it. If the string the caller passed you was an NSMutableString, its value could change later, and it will change in your class as well. This is probably not what you want, so I'd advise doing this:
+ (void)myClassMethod:(NSString *)param {
[_myString release];
_myString = [param copy];
}
The copy method makes a copy and sets the retain count to 1, so you're all set as far as retaining the variable is concerned. And, as an extra bonus, if the caller does pass you an NSString, that class is smart enough to know that its value can't change, so it simply retains itself to avoid making a copy of the object. How clever is that?