Releasing Singletons - ios

I was wondering how you would release a singleton
+ (DSActivityView *)activityViewForView:(UIView *)addToView withLabel:(NSString *)labelText width:(NSUInteger)labelWidth;
{
// Not autoreleased, as it is basically a singleton:
return [[self alloc] initForView:addToView withLabel:labelText width:labelWidth];
}
When analysing this using the analyse tool i get the following error :
Potential leak of object on line 90. which is the line that returns.
I have tried autorelease that solves the error message problem but im not convinced its the right solution since i read that autoreleasing singletons is not good. Would someone be able to assist me in identifying how best to release this object?
Thanks

The reason why the analyzer gives you the warning is, basically, the method name:
+ (DSActivityView *)activityViewForView:(UIView *)addToView withLabel:(NSString *)labelText width:(NSUInteger)labelWidth;
according to Objective-C conventions, all method names starting with "create"/"new"/... return a retained object; your method falls under the category of convenience constructors, which are expected to return autoreleased objects, hence the warning.
On the other hand, you say this is a singleton, but in fact it is not. So, you could possibly end up calling this method more than once and thus have an actual leak. A basic way to make your method safer (and more singleton-like) is:
+ (DSActivityView *)activityViewForView:(UIView *)addToView withLabel:(NSString *)labelText width:(NSUInteger)labelWidth;
{
static DSActivityView* gDSActivityViewSingleton = nil;
if (!gDSActivityViewSingleton)
gDSActivityViewSingleton = [[self alloc] initForView:addToView withLabel:labelText width:labelWidth];
return gDSActivityViewSingleton;
}
This would both make the analyzer relax and give you more safety in front of the possibility of misuse of the method.

Use autorelease. There's no reason not to. Basically ownership of the object belongs to the object, so you're never going to be able to manually release it. As its a singleton it doesn't matter if you don't own it because presumably next time you call it and need it in scope you'll use another convenience method and it will get instantiated again.
If you want to have ownership of the object then you will need to instantiate it as normal and then you will be able to retain and release it.
Also, read sergio's edit about it not being a "proper" singleton. :p
Also, if you can, convert to ARC and you won't have to worry about this!

U are doing it wrong. Consider:
If you calling activityViewForView multiple times, you won't get get the same object over and over again. It only would initialize a new object and give you the pointer to it!!!
To make this thing a singleton, you have to store the created object in a constant variable and make sure, you have a reference to this object all the time your app is running (for instance declare your pointer to this object in appDelegate).
Then every time you call activityViewForView you have to check the constant variable if it is pointing to a valid object. If so, return the valid object, if not, create it and store it in your constant static variable (creation is done only once).
If you do use ARC you're all set. If not, release your object (use dealloc method)

Related

Can an object be deallocated during method execution?

Let's assume that we create an instance of class var foo: Foo? = Foo() on the main thread and we call some time consuming instance method bar of Foo on another thread, after a short time we set foo to nil on main thread. What happens with the execution of bar, in my understanding bar should still continue its execution since invoking instance method implicitly passes self as the first argument, so even those the last explicit ref to foo was broken we still have a ref inside of a method and it should be good. But then I found this stackoverflow post which completely breaks my understanding. So, can somebody confirm/deny the fact that object cannot be deallocated during its method execution
Short answer is that your belief is correct, and you're looking at a question that's not relevant to Swift.
Your link is to non-ARC Objective-C. Swift always uses ARC, and ARC is very conservative about retains. Consider the following Objective-C call:
[target runMethod: parameter];
Under ARC, this is (conceptually) transformed into:
[target retain];
[parameter retain];
[target runMethod: parameter];
[parameter release];
[target release];
retain and release are atomic, thread-safe calls.
A similar behavior exists in Swift. Because of this, as a general rule (in the absence of Unsafe), a variable cannot "disappear" while you'll holding onto it.
This is the implementation detail. The better way to think about it is that by default variables and parameters are strong, and an object cannot be destroyed while there is a strong reference. This matches your understanding.
Prior to ARC, though, you needed to insert extra retains and releases yourself to protect against this kind of situation, and it was very common not to. (Prior to 10.6, most ObjC was single-threaded.)
Even without threads, there are ways this can go astray without ARC. Since callers often didn't immediately retain returned values if they only needed them temporarily, it was possible to get dangling pointers even without multiple threads. For example, with a trivial accessor with no memory management, this can crash:
NSString *name = [person name];
[person release];
[self doSomethingWithName: name];
This is why you often see old ObjC getters written in the form:
- (NSString*) title {
return [[title retain] autorelease];
}
This made sure that the returned value would survive until the end of the event loop even if self released it or self was deallocated.
Swift does similar things via ARC, but as the name suggests, it's all automatic.

__autoreleasing for return value in ARC Objective-C

According to Cocoa's "Create Rule" a method that returns a newly instantiated object must begin with either new, create, or copy if ownership is transferred to the caller.
Let's say I have a class that implements a factory method called (NSObject *)getCorrectObject.
This method will return a new instance of the correct subclass of the callee (determined by some internal state of the callee). Technically this method does not follow the "Create Rule" and could lead to memory leaks in non-ARC environments.
Would it be possible to instead use (NSObject *__autoreleasing)getCorrectObject to avoid using new or create in this case?
In non-ARC I would return an autoreleased object, but I'm not entirely sure if __autoreleasing works for anything other than In/Out parameters.
According to Cocoa's "Create Rule" a method that returns a newly instantiated object must begin with either new, create, or copy if ownership is transferred to the caller.
This isn't called the Create Rule (and isn't correct). The Create Rule is a Core Foundation rule related to the words Create and Copy. Cocoa has a different rule related to “alloc”, “new”, “copy”, or “mutableCopy”.
Let's say I have a class that implements a factory method called (NSObject *)getCorrectObject.
Then it would be incorrectly named. Starting a method with get indicates that it returns a value by reference. The correct signature would be:
+ (BOOL)getCorrectObject(NSObject**)result;
This method will return a new instance of the correct subclass of the callee (determined by some internal state of the callee). Technically this method does not follow the "Create Rule" and could lead to memory leaks in non-ARC environments.
That is not based on whether it is a new instance. It's based on whether it includes an unbalanced retain.
Methods that begin with “alloc”, “new”, “copy”, or “mutableCopy” should return an object with one unbalanced retain. Other methods should return an object that has an equal number of retain and autorelease attached to it.
If for some reason you have to violate these naming rules (and you really don't want to violate these rules), the correct way to indicate it to ARC is by using NS_RETURNS_RETAINED (see Foundation/NSObjCRuntime.h for all the macros). This only assists ARC in correctly fixing your memory management when dealing with mixed ARC/Retain code in cases where it is impossible to fix your incorrect naming. Pure ARC code doesn't need this; it'll balance out either way. Pure Retain code won't be helped by this. The caller has to do the right thing (and so has to just know that you did it wrong and compensate).
Note that as long as you're using ARC throughout the project (and you really, really should be), most of this won't matter a lot in practice. ARC will balance everything out for you pretty much no matter what you name things, since you're not in charge of adding the retains, releases, and autoreleases anyway.

Asynchronous methods called inside `-dealloc` could generate unwanted zombie objects

As I was walking through some line of codes I stumbled upon this problem a couple of days ago,
- (void)dealloc {
...
[self.postOfficeService deregister:self];
...
}
Where the de-registration from the Post Office Service is an asynchronous operation, even if it's not self evident from the interface as there's no block or function passed to the postOfficeService.
The internal implementation of postOfficeService's -deregister method is something like that
// -deregister:(id)formerSubscriber implementation
//some trivial checks here
// deregister former subscriber
dispatch_asynch(_serialQueue, ^{
[self.subcribers removeObject:formerSubscriber];
});
...
The container, self.subscribers, does perfectly its job and contains only weak references. I.e. it is a NSHashTable.
As long as the deregistration method got called within the dealloc method, I keep on getting a crash while postOfficeService is trying to remove the former subscribers from its list inside that asynch block, which is used for thread safety purposes I guess.
Adding a breakpoint on [self.subscribers removeObject:formerSubscriber], it's possible to notice that the formerSubscriber object is always a NSZombieObject. That's the reason for crashes.
I know that it's possible to get thread safety for deregister method without incurring in this problem - I figure it should be enough use the dispatch_synch in lieu of the dispatch_asynch version
I think this is one of the reason why asynchronous methods shouldn't be called within dealloc methods.
But the question is how's possible to constantly get NSZombie objects even if we are in an ARC environment and the container objects is a NSHashTable (so it should be working I guess)?
The rule is: When dealloc is called, the object will be gone once dealloc returns to its caller (whoever called release when the reference count was 0), and nothing is going to prevent this.
Before ARC, you might have tried to retain an object inside dealloc - doesn't help; once dealloc is called the object will go (and dealloc will be called only once for it, in case you do a retain / release inside dealloc). ARC does the same, just automatically.
Using ARC doesn't means all your memory problem magically disappeared.
What happened is
[obj release] called by ARC
[obj dealloc]
[obj.postOfficeService deregister:obj]
[obj retain] - sorry you can't cancel the deallocation process
dispatch_async
free(obj) - from this point, obj is a zombie
GCD scheduling tasks
dispatch_async execute task
use obj - crash
The correct solution is use dispatch_sync to make sure you not trying to use object after it is deallocated. (be careful about dead lock)
Don't call asynchronous cleanup methods from dealloc. It's just not a good idea. Your -deregister should be synchronous.
NSHashTable stores pointers - it's the equivalent of __unsafe_unretained or assign - UNLESS it was created using +weakObjectsHashTable or the equivalent set of options (NSHashTableZeroingWeakMemory and NSPointerFunctionsObjectPersonality). If it was not created that way, it is quite likely you will have values pointing to zombie objects.
The question of "why am I getting zombies" is best answered by profiling your application with the Zombies template in Instruments and stimulating the required behavior.
I agree with the others that you should probably avoid asynchronous cleanup in your -dealloc method. However, it may be possible to fix this by making the parameter to -deregister: __unsafe_unretained. That method would then have to treat the pointer purely as a opaque value. It must not dereference it or message it. Unfortunately, you don't control the implementation of NSHashTable and can't guarantee that. Even if NSHashTable could be relied upon, the interface of -removeObject: takes an implicitly strong object pointer, so ARC might retain the pointer when it's copied from the unsafe unretained pointer.
You might use the C function API for hash tables (e.g. NSHashRemove()) as suggested in the overview for the NSHashTable class.

XCode - Writing static analysis friendly code

I'm starting to make use of static code analysis to find memory management problems in my code. I've found it very useful, but there are a couple of bits of code I've written that I'm sure aren't causing memory leaks (instruments doesn't report any) but are being reported by the analyser. I think it's a question of me writing the code in a non-friendly manner. Here's an example
for (glyphUnit *ellipsisDot in ellipsisArray) {
CGPathRef newDot = CGPathCreateCopyByTransformingPath(ellipsisDot.glyphPath, &ellipsisTransform);
CGPathRelease(ellipsisDot.glyphPath); // Incorrect decrement of the reference count of an object that is not owned at this point by the caller
ellipsisDot.glyphPath = newDot;
}
where glyphUnit is a simple custom class that has a GCPathRef as a property, which the custom class releases in its dealloc method. So in this loop I'm transforming the path and storing it in anewDot then releasing the original glyphPath so I can assign the newly created one to it. I can see how this is getting the code analyser confused, with it giving a message I'm decrementing an object I don't own. Is there another way swap in the new path without confusing it?
It should be,
for (glyphUnit *ellipsisDot in ellipsisArray) {
CGPathRef newDot = CGPathCreateCopyByTransformingPath(ellipsisDot.glyphPath, &ellipsisTransform);
ellipsisDot.glyphPath = newDot;
CGPathRelease(newDot);
}
You are creating newDot by doing CG CreateCopy operation and you need to do release on that variable. So the analyser is warning that you dont own ellipsisDot.glyphPath param to release it. You are trying to release the wrong param here. When you put that release statement in the second line as in question, ellipsisDot.glyphPath and newDot are pointing to two separate instances. Only on the third line, you were assigning newDot to ellipsisDot.glyphPath.
It turns out that I forgot about defining setters in my custom glyphUnit class. Being in the ARC world for objects and used to synthesizing my methods I had forgotten the need to manage my retain counts for core foundation references. I had been releasing glyphPath in my dealloc, but was not using a setter method. As #Sven suspected, I was simply using a synthesized assign and making up for my lack of setter method by doing some less than intuitive releases in my code snippet above. I've now added a setter method as below to glyphUnit
- (void)setGlyphPath:(CGPathRef)newPath
{
if (_glyphPath != newPath)
{
CGPathRelease(_glyphPath);
_glyphPath = CGPathRetain(newPath);
}
}
After adding this, I now had the necessary retain in place to change my code snippet to the one #ACB described and my code ran nicely (without it, it obviously caused an EXC_BAD_ACCESS).
Kudos to #Sven for inferring my mistake and setting me in the right direction... no pun intended.

What is the memory management problem with this bit of code?

The XCode analyzer tells me there is a problem at line 4 — return [originalError copy]; — but I don't see it. Help me please?
- (NSError *)errorFromOriginalError:(NSError *)originalError error:(NSError *)secondError
{
if (secondError == nil) {
return [originalError copy];
}
// ...
}
The problem description is:
Potential leak of an object allocated on line 203
Method returns an Objective-C object with a +1 retain count (owning reference)
Object returned to caller as an owning reference (single retain count transferred to caller)
Object allocated on line 203 is returned from a method whose name ('errorFromOriginalError:error:') does not contain 'copy' or otherwise starts with 'new' or 'alloc'. This violates the naming convention rules given in the Memory Management Guide for Cocoa (object leaked)
Potential null dereference. According to coding standards in 'Creating and Returning NSError Objects' the parameter 'error' may be null
The third issue seems to suggest I should either change the name or the behaviour of the method further. Any suggestions on that? The method is derived from the errorFromOriginalError:error: method described in Apple's Core Data Validation document. Its purpose is to combine originalError and secondError so that secondError is a sub-error of originalError.
My addition tries to ensure that the method still works if there is no actual secondError. Since a new error object is created if secondError is not nil, I wanted to recreate that in the case displayed above by simply copying the error object.
You are making a copy of originalError, but your function name implies that the returned object will be autoreleased. Try
return [[originalError copy] autorelease];
[originalError copy] creates a new object with a retain count set to 1. It would then be the responsibility of the calling method to release that object. If you're doing this then it isn't necessarily a problem, but it's probably a better ideas to autorelease it.
ie
return [[originalError copy] autorelease];

Resources