why [self.property release] will cause the static analyzer to show an "incorrect decrement of the reference count" error? [duplicate] - objective-c

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Incorrect decrement of the reference count of an object that is not owned at this point by the caller
Why shouldn't I use the getter to release a property in objective-c?
So, I get that using [self.myProperty release] is discouraged (Apple itself recommends not to). Although it appears to me that it COULD lead to problems in some cases, not all cases. Is this correct? More importantly: I don't get why using a syntax like [self.myProperty release] in my -dealloc method(s) will cause the static analyzer to show an "incorrect decrement" error. Despite any other reason discouraging such a syntax, my class still owns its properties (which I have declared with "nonatomic,retain") so why the warning?
I've been reading several posts on this but it seems I can't really wrap my mind around it.
Some of them go into details about the possible side effects of using such a syntax, but what I really want to know is the reason behind the "incorrect decrement" error.
Any help would greatly be appreciated.

Cocoa memory management has a concept of "ownership" which is expressed most succinctly in the rule: If you call new or alloc, or send retain or copy to an object, you own the result, and are responsible for sending release when you're done with it. Otherwise, you do not own it, and you must not send release.
Instance variables, basically by definition, contain objects that the instance owns. You need the objects to be valid for the life of the instance, so you create them with an ownership-granting method in init:
// myDinkus and creationDate are ivars of whatever class this is.
// They are assigned to with owned references.
myDinkus = [[Dinkus alloc] init]; // ownership due to alloc
creationDate = [[NSDate date] retain]; // ownership due to retain
These now need to be sent release when the instance is done with them; generally speaking, this will be in dealloc.
Getter methods don't return owning references. This is the way it should be; when your code, e.g., asks a label for its font color, it doesn't need that color object to stick around. Or if it does, it must explicitly take ownership by sending retain. Giving it ownership by default would create headaches at best and possibly leaks.
That established, [self.myProperty release] causes the static analyzer to complain because it's a violation of the ownership concept. The object returned from [self myProperty] isn't owned by the caller. The fact that it just so happens to be the same object as an ivar that is owned by the caller is irrelevant. (In fact, it might not be the same; the getter might return a copy of the object it represents, for example. It might construct an entirely new value based on a group of ivars. It's even possible for there to be no ivar that corresponds to a getter.)
Since objects which are not owned must not be sent release, doing so to the result of a getter is incorrect.
There are other, practical, reasons not to do this (covered quite well, especially by Justin's answer in the question proposed as dupe), but that's the reason the analyzer is complaining.

Fundamentally, you're sending a release message to an object that you haven't sent a retain to (at least not explicitly). The static analyzer will expect to see balanced retain/releases.

When you declare your property as nonatomic,retain you are handing responsibility for releasing the value to the property's setter.
If you do a [self.myProperty release] then your property still contains its old value and any subsequent setting of that property will do a release on that old value - but you've already released it, so now it is over-released... Hence the warning.
To release the value you should use self.myProperty = nil - the setter will release the old value and assign nil to the property.

Related

Weak and strong property implementation

I want to better understand strong and weak pointers implementation, and i figure out assumptions, about how their setter methods would look like (correct me if i wrong please).
First, strong pointer, look like:
- (void)setObj:(NSObject*)Obj // Setting Strong Obj
{
//First, check either we trying to set old value again
if (_Obj == Obj)
{
return;
}
NSObject* oldObj = _Obj;
_Obj = [Obj retain];
[oldObj release];
// Set pointer to old "chunk" of memory, containing old value,
// assign new value to backed instance variable and release
// old value
}
That is my assumption of construction, that strong setter may look like. So, my first question is - am i correct in my assumption?
Second, weak reference. I guess, it should look similar, but exclude retain.
- (void)setObj:(NSObject*)Obj // Setting Weak Obj
{
if (_Obj == Obj)
{
return;
}
NSObject* oldObj = _Obj;
_Obj = Obj; // setting value without incrementing reference count
[oldObj release];
}
Is that correctly assumption, about how weak reference work?
Ok, one more question. Consider a situation like that (in Manual Memory Management):
- (void)testFunc
{
strongObj = val; // Retain count about >= 2
weakObj = val; // Retain count about >=1
}
// Now strongObj lives in memory with value of val, with retain count >=1
// weakObj is destroyed, since after end of a scope (function body) it retain count decreased by 1
So, actually i want to know, whether retain count decremented each time, when method that own variable finishes?
I know that question is familiar to many developers, but, i want clarification in that cases. Thanks.
Your strong implementation is correct.
The weak one is wrong. You are not allowed to release the value if you have not previously retained it. You would just set the new value without issueing memory management calls here.
Then again, that wouldn't really be weak, but assign. The special thing about weak is that the reference is zeroed out of the referenced object is deallocated.
For the first and second Q I refer to #rmaddy's comment and Christian's answer.
So, actually i want to know, whether retain count decremented each time, when method that own variable finishes?
First I want to be more precise: When you say "when method that own a variable finishes" you probably mean "when a local strong reference variable of automatic storage class loses its extent". This is not exactly the same. But it is what you likely wanted to say. ("A usual local var.")
In this case it is correct that the referred object is released.
But things are more difficult behind the scenes. I. e.: What happens if the local var (more precise again: the referred object) is returned? What happens in this case, if the method is ownership transferring or not?
The basic problem is that an automatic reference counting has to take edge cases formally into account, even in "usual" code things couldn't break. A human developer can say: "Oh, there is a very special situation the code can break, but I know that this never happens." A compiler cannot. So ARC typically creates very much memory handling calls. Fortunately many of them are optimized away.
If you want to have a deep view into what is done in which situation, you have two good approaches:
Read clang's documenation, which is more precise than Apple's by far, but it is more complicated.
Create a class in a separate file that implements the methods for manual reference counting (-retain, -release, …) and log the execution. Then compile it with manual reference counting, which is possible through compiler flags. Use that class in ARC code. You will see, what ARC does. (You should not rely on the results, because they are subject of optimization and the strategy can change in the future. But it is a good tool to understand, how ARC works.)
It may be helpful to think about strong and weak references in terms of balloons.
A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.
A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.
A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.

How does retainCount work?

I have a problem with retainCount
NSLog(#"%i", [self.albumReceiver retainCount]);
self.albumReceiver = [[[FacebookAlbumsDelegateReceiver alloc] init: self] autorelease];
NSLog(#"%i", [self.albumReceiver retainCount]);
The retain count on the first line is 0 but when it gets to third line is 3.
The property on self.albumReceiver is retain property... But as far as i can see it should be 2 where other later retain count should went to 1 since it was autorelease later.
NSLog(#"%i", [self.albumReceiver retainCount]);
albumReceiver = [[[FacebookAlbumsDelegateReceiver alloc] init: self];
NSLog(#"%i", [self.albumReceiver retainCount]);
the retain count start with 0 and in this case the second retain count print 2....
Can somebody give some idea of how this retain and release work....
I thought without 'self' keyword, it will ignore the setter call is it? But if i put autorelease on the second example, i will have error.
Firstly, the retain count is an implementation detail that you should not be overly concerned with. You should really only care about ownership.
Having said that, the explanation for what you are seeingis as follows:
The retain count on the first line is 0
That's because self.albumReceiver is nil at that point. On real objects, you will never see a retain count of 0 (in the current implementation of Foundation).
when it gets to third line is 3
Normally you would expect the retain count to be 2, +1 for the alloc and +1 for assignment to a retain property. However, the init: method might cause some other object to retain it, so might the setter for the property. Another object observing the property might choose to retain the object too. In short, unless you know the exact implementation of all the methods involved and you know for sure nothing is using KVO on albumReceiver, all you can say about the retain count is that self has ownership of it (NB ownership is not exclusive, other things may also have ownership). This is why you shouldn't pay too much attention to retain counts.
Can somebody give some idea of how this retain and release work
Yes. You need to think in terms of ownership. Certain methods give you an object that you own. These are any method starting with alloc, any method starting with new, any method starting with copy or mutableCopy and -retain. If you receive an object in any other way, you do not own it. That includes receiving them as a return result of a method, ass parameters of a method or as by reference parameters of a method or as global or static variables.
If you own an object, you must relinquish ownership by either releasing or autoreleasing it, or it will leak. If you do not own an object, you must not release or autorelease it.
I find that it is best to think of "you" in the above as meaning "the scope in which the object reference was declared".
Anyway, I recommend you to read Apple's Memory Management Rules for the definitive explanation and not to trust answers here. If you look at the original edit for this answer, you'll see that I got the rules slightly wrong because they have been tightened up since I last read them.
Do not use retainCount. (For situations where it’s appropriate to use it, see this website.) Further reading: blog post by bbum, previous SO thread one, thread two. Also note that retainCount is deprecated in recent SDKs. It’s a good idea to pay attention to the deprecation warnings, and even better idea to turn all warnings into errors.
It is generally a bad idea to pay any attention to the retainCount of an object in Objective-C because it is usually impossible to know which secret parts of the frameworks feel a need to retain the object.
In the case you cite where you are adding the object to the autorelease pool, the autorelease pool will presumably be retaining the object until it comes time to flush the pool (during the runloop). This probably explains why the retain count is higher for the autoreleased object.
Note the use of the words "presumably" and "probably" in the above paragraph. I have no idea if this is actually what is happening inside the Cocoa/Cocoa Touch frameworks. This is the problem with using retainCount, you have no way of knowing what the retain count should be at any moment.
If you retain the object (or create it with a method name that contains alloc, copy, mutableCopy or new), you release it. The frameworks are free to also retain the object and they will release it when they are ready. When the retain count reaches zero it will be dealloced.
Update: Having looked at the GNUStep source code for NSObject and NSAutoreleasePool my possible explanation above probably isn't what is happening. However, I have no way to check for sure because I can't see Apple's implementation of these two objects. Even more reason not to trust retainCount or any inferences from it.
The only rule that really exists in environments with manual memory management is
If you use alloc, copy, mutableCopy, new
release it. Otherwise DON'T. retainCounts don't really work for debugging. See here

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.

Objective-C, ownership and class methods

First off, I'm a Objective-C newbie. :)
I've learned that anything that starts with alloc, new, and copy, gives the caller ownership of the returned object. Does this also apply to class methods? I'm guessing it does, and a recent crash in one of my unit tests seems to confirm it. Apple's Advanced Memory Management Programming Guide doesn't say anything whether there's a difference between class and instance methods.
Update
What I mean that it also applies to class methods is really the "inverse". For instance, NSDecimalNumber has a class method called +decimalNumberWithDecimal:. It seems to return an auto released object (if I release it explicitly, a crash occurs shortly after that). In hindsight, the answer to my question is obvious, as Apple's guide refers to new and alloc as ownership-giving methods, and they're all class methods. Sorry for taking up your valuable time. :)
Also alloc and release. init does not indicate ownership, you are likely mixing that up with alloc. You can memorise it easily with the mnemonic NARC.
If you are naming any class methods init, copy or retain, you should stop that. Those are methods that only make sense in the context of instances. alloc and new are class methods and should only be used in that context. Don't name instance methods alloc or new.
The reason why the guide doesn't say that it applies to both instance methods and class methods is that the methods in question are clearly a mixture of both, so it's obviously the case.
Yes this applies to class methods since alloc and new are class methods which return ownership to the caller. The prefix of copy or mutableCopy should be used for instance methods returning ownership.
Edit For The Update:
You are correct a method like +decimalNumberWithDecimal: is expected to return an autoreleased object, therefore there is no reason to release it. If however they decided to name the method +newNumberWithDecimal: then you would have ownership of the returned object and need to release it. Clang static analyzer will actually complain if you prefix a method with new and return an autoreleased object.
Actually, this is almost correct. alloc, new, and copy give you ownership of the returned object. These are class methods. Other class methods should return an autoreleased object. Instance methods should also return an autoreleased object.
init does not effect ownership and should be use in conjunction with alloc as follows.
[[SomeCoolClass alloc] init]
new is usually the same thing as the above and is sometimes described as "almost deprecated" because it is a throwback to the NeXT days when the allocation and initialization were done in the same step and could not be plot apart as we do today with alloc and init.
Release does not effect ownership, but should only be used on object you already own. Otherwise a crash is likely to occur.
Retain also does not affect ownership, but should only be used on an object you already own. Otherwise the object may not be deallocated when it should be. The result could be a crash, but it can also be very very strange behavior that is difficult to troubleshoot because messages may be sent to the original object that was supposed to have been deallocated instead of a new object pointed to at the same address.

How do I find out if I need to retain or assign an property?

Are there any good rules to learn when I should use retain, and when assign?
Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.
The only common exception is weak references, where you want to keep a pointer to an object but can't retain it because of reference cycles. An example of this is the delegate pattern, where an object (for example a table view) keeps a pointer to its delegate. Since the delegate object retains the table view, having the table view retain the delegate would mean neither one will ever be released. A weak reference is used in this case instead. In this situation you would use assign when you create your property.
I would think that when working with objects you would almost always use retain instead of assign and when working with primitive types, structs, etc, you would use assign (since you can't retain non-objects). That's because you want the object with the property deciding when it is done with the object, not something else. Apple's Memory Management Guide states this:
There are times when you don’t want a
received object to be disposed of; for
example, you may need to cache the
object in an instance variable. In
this case, only you know when the
object is no longer needed, so you
need the power to ensure that the
object is not disposed of while you
are still using it. You do this with a
retain message, which stays the effect
of a pending autorelease (or preempts
a later release or autorelease
message). By retaining an object you
ensure that it won’t be deallocated
until you are done with it.
For discussion around using copy vs retain, see this SO question.
I know this was an old question, but I found these guidelines from the uber guru Matt Gallagher, super useful: http://cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html. In my case, I had a "retain hell" of my own making for having a hard reference to a parent object.
If you intend to keep the object and use it, use retain. Otherwise, it may be released and you'll end up with errors with your code.