Using [NSObject load] to initialized system with no autorelease pool - ios

I am writing an iPad application using the Xcode 4.3.2 and the iOS simulator. I have a series of classes that I want to register with a singleton at start up so that other classes can request services through that singleton that are provided by these registered classes.
To effect this behavior I have been relying on overriding the load class method on NSObject. However, I discovered that all the code that gets executed by the load method occurs outside the main function before there is any opportunity to set up an autorelease pool. I'm using some 3rd party technology in my application that current prohibits the use or automatic reference counting, so I need to rely on an autorelease pool to help manage the lifetime of created objects.
During the registration process, a number of messages appear in the debug console for the simulator complaining about autorelease being called with no autorelease pool. One of these is related to a dictionary allocated by the singleton. Other are related to block objects that get copied from the stack and store in that singleton dictionary.
It is not clear to me how serious these debug messages are. I suspect the allocation of the dictionary may not be problematic as the singleton should exist for the lifetime of the application and that dictionary will likely never be released. Likewise the block stored in the dictionary should persist as well, so I'm wondering if I don't need to bother calling autorelease on them after calling the copy method.
Or maybe there is another way to accomplish what I want with out having to resort to the current technique that might be less problematic
What can people suggest about this issue?

You should have better luck overriding +[NSObject initialize] rather than load, initialize is called the first time the class is referenced, rather than when the image the class is in is loaded. This will give you better handing of all this.

A good approach is to use dispatch_once_t, which is only executed once per runtime, across all threads:
+ (id)sharedInstance
{
static dispatch_once_t once;
static SingletonClass *sharedInstance;
dispatch_once(&once, ^ { sharedInstance = [[self alloc] init]; });
return sharedInstance;
}

Related

Objective C - Creating singleton using shared instance

I have doubts regarding the creation of singleton class in Objective-C/iOS.
Where ever I see the trick to create a singleton class in objective-C is this code
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
Whenever I call [MyManager sharedManager] of course I get the same address. However, I can also write [MyManager new] in which case the address is different.
1.Isn't the concept of singleton class is that it restricts the instantiation of a class to one object?
2.If we can create another object its not a singleton anymore, is it?
In my iOS app I tried [UIApplication new]. I got an exception in runtime. Now this I get. You cannot make another instance of UIApplication since its a singleton class.
So why the use of shared instance considered to be the way of creating a singleton class or have I got this all wrong?
The sharedManager is the convenience method you'd use to access the singleton instance. While this doesn't guarantee that there will be only one instance of that manager over the app, if everyone is using sharedManager then there will practically exist only one instance of that manager.
This kind of singletons are singletons by convenience, not by implementation. You should use them, for multiple reasons:
you can unit test them, by calling alloc init in your unit tests and making use of that brand new allocated object
it makes your life easier if decide to later refactor the manager and no longer use it as a singleton if you consider it from the begging like a regular object to work with
Of-course, you can make a singleton by-the-book by overriding the init and allocWithZone: to either return the only instance or by raising an exception, however I'm not sure they'd worth the effort.
There's a very good tech talk regarding singletons held by Misko Hevery in the Google clean code talks playlist, the link to the video: here. This kind of singletons are referred as lower case S singletons, not capital S ones in the video, and Misko explains very well why they are preferred.
It doesn't break singleton concept. You choose your way to implement what you want. If you want to create only singleton instance, you can make run error by override init function:
[NSException exceptionWithName:NSInternalInconsistencyException
reason:#"bla bla bla..." userInfo:nil];
or
you can override it to force return to shared instance.
Of course, you can. But it not recommend if you are using singleton.
Objective-C uses a pragmatic approach. Your +sharedManager method returns a singleton. If someone is stupid enough to call [SingletonClass new] or [[SingletonClass alloc] init], that's their problem. They'll get what they deserve. There is no reason to prevent people from shooting themselves in the foot if that is what they want to do.
There are millions of programming errors that people can make and that the developer of a class or the compiler cannot prevent. No point wasting effort on preventing this particular error.

Possibilities of Singleton instance getting deallocated automatically

I am creating singleton instance as below:
+(MySingleton*)sharedInstance {
static MySingleton sharedObject = nil;
static dispatch_once_t predicate = 0;
dispatch_once(&predicate, ^{
sharedObject = [[MySingleton alloc] init];
});
return sharedObject;
}
What are the possibilities of sharedObject getting deallocated automatically?
How can I be sure that sharedObject will remain in memory until app is terminated?
As another answer rightly points out, this shared singleton will never be deallocated. There are two parts to answer "why", both of which come from the following line:
static MySingleton * sharedObject = nil;
First, static. static, when used inside of a function like this, modifies the lifetime of a variable, changing it from automatic, the implicit default, to static. This means that this variable exists for the entire lifetime of the program.
Second, this declaration makes sharedObject a strong reference. Variables in Objective-C are strong by default, but to be pedantic, you could have written:
static __strong MySingleton * sharedObject = nil;
So: we have a variable that lives for the entire duration of your program (static), and that maintains a strong reference to the object it represents (__strong). With these two pieces of information, plus the fact that you never change the object to which the variable points, you can deduce that sharedObject will never be deallocated.
0 possibility. It will never be released, static keeps it with strong reference. In ARC world you can't just release something without first retaining it.
I ran into one very dubious case where it can get released and cause unhappy problems, so while uncommon something to be careful of.
If a you pass its memory address a third party low level library ie. as user_data (or perhaps a low level c library you have created) and that library releases the memory. You would not expect external libraries to release user_data you provide but that was the case with a web sockets c library I was using.
sharedObject will be released after its included functions complete and after releasing contained blocks. so that, dispatch_once most probably releases running block after run it once. it means, it will be released just after called onece.

ObjC How to dispose of a Singleton Object when the app is NOT quitting

My (iOS7 / ARC) app has the concept of "log in" where a user connects to a remote server. For the duration of the users logged-in session, I have some singleton objects to handle low level aspects (sockets, process incoming messages, etc). When the user logs out, I would like to dispose of these singletons and then recreate them when the user logs back in (assumed is the app is not dying off or being quit).
The singleton is created so:
static MYChatMessageManager *messageManager = nil;
static dispatch_once_t onceToken = 0;
+(MYChatMessageManager *) messageManager
{
dispatch_once(&onceToken, ^{
messageManager = [[self alloc] init];
// Do any other initialisation stuff here
});
return messageManager;
}
and I defined a class method which I thought would accomplish the task
+(void) shutdown
{
onceToken = 0;
messageManager = nil;
}
When I call this, I would expect that the -dealloc method of the singleton instance to be called since ARC should see no one has reference to it. However, -dealloc is not being called and in the debugger, after the +shutdown is called, I stop the app (shutdown has run and several seconds late I just stop the app) and examine the object at the memory location I have for messageManager (gotten from lldb earlier, not in code) and it still has a retainCount of 1. I can identify no place in my app that any variable or object pointer is assigned this object which would increment the retain count through ARC.
I am not sure what I can do to make this singleton go away.
Use the Allocations Instrument, turn on reference event tracking, and then see what is holding the final reference(s).
Which you have done, more or less (found the last reference at least).
However, this is bad design and the code is buggy. First, as noted in comments, a dispatch_once_t cannot be reset.
Secondly, and the bigger issue, you should never destroy a shared instance and, by implication, there should be no critical logic in the class's -dealloc method (which, btw, is more of a general rule than one specific to shared instance classes).
By the definition of "shared instance", that object should stick around forever. If it needs to transition between "active" and "shutdown" states, then add that logic in a fashion that does not connect it to the object's lifespan.
There was a sneaky block handler based reference to the object that a third review of the code uncovered. Sorry for the false alarm.

Confusion about ARC , AutoRelease

I am new to IOS development and I have started to learn objective c to program towards IOS 7. and as I know, it is way easier to code now than it has been before because of the Automatic reference counting.
there are a couple of things I do not understand . in MAIN method we have the autoreleasepool block, so my first question is that in order to enable ARC , the code has to be inside this block? if no, then what is the difference between the code that is inside autoreleasepool and the rest those aren't?
my second question is that when I am writing my IPHONE programs , I have bunch of classes and non of those codes are inside "autoreleasepool" , only the code inside the MAIN method.
int main(int argc, char * argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([HomepwnerAppDelegate class]));
}
}
so , does this mean that this block somehow magically gets applied to all lines of code inside any other classes of the same program?
My last question is that whether with ARC or without it, if we had a declared pointer variable inside a method, does the object gets released/destroyed when the method returns/exit?
assume we have a method like this :
- (void)doSomething {
NSMutableArray *allItems = [[NSMutableArray alloc] init];
NSString *myString = #"sample string";
[allItems addObject:myString]
}
then when we call this method and it exits, what would happen to those local variables defined inside the method ? is there any difference in the outcome if we are using ARC or not ? (Object are still in the memory or not)
Autorelease pools predate ARC by about 15 years. Cocoa uses a reference-counting memory management scheme, where (conceptually, at least) objects are created with a reference count of 1, retain increases it by 1 and release decreases the count by 1, and the object is destroyed when the count gets to 0.
A problem with this scheme is that it makes returning an object kind of awkward, because you can't release the object before you return it — if you did, it might be destroyed before the other method got to use it — but you don't want to require the other method to release the object either. This is where autorelease pools come in. An autorelease pool lets you hand an object to it, and it promises to release the object for you later. Under manual retain/release (the way we used to do things before ARC), you did this by sending autorelease to an object.
OK, so then ARC comes into the picture. The only thing that really changes with ARC is that you aren't the one writing retain, release and autorelease anymore — the compiler inserts them for you. But you still need an autorelease pool for autoreleased object to go into.
As for your second question:
My last question is that whether with ARC or without it, if we had a declared pointer variable inside a method, does the object gets released/destroyed when the method returns/exit?
assume we have a method like this :
- (void)doSomething {
NSMutableArray *allItems = [[NSMutableArray alloc] init];
NSString *myString = #"sample string";
[allItems addObject:myString]
}
then when we call this method and it exits, what would happen to those local variables defined inside the method ? is there any difference in the outcome if we are using ARC or not ?
If you're using ARC, the compiler will release any objects referenced by local variables. If you're not using ARC, you'd need write [allItems release] yourself, because the variable going out of scope does not magically cause the object it references to be released.
new to IOS development
Best not to worry, Automatic means that you mostly concentrate on other things ^)
does this mean that this block somehow magically gets applied to all lines of code inside any other classes of the same program
Yes. You're in main function, so all the code that is executed has to be inside this function - your app will terminate once it ends. Unless you create a separate thread, but it's hard to do that by accident.
the code has to be inside this block
As said above, all of your code on main thread will execute within this block.
what would happen to those local variables defined inside the method
You're guaranteed that they will be destroyed before returning.
in MAIN method we have the autoreleasepool block, so my first question is that in order to enable ARC, the code has to be inside this block? if no, then what is the difference between the code that is inside autoreleasepool and the rest those aren't?
ARC is enabled by corresponding Objective-C compiler setting. If you create a new project in the latest version of Xcode it will be enabled by default.
The #autorelease keyword places code inside the curly brackets into autorelease pool scope. Autorelease pools are used both with ARC and manual memory management.
my second question is that when I am writing my IPHONE programs , I have bunch of classes and non of those codes are inside "autoreleasepool" , only the code inside the MAIN method.
iOS applications are event based. Main thread starts event loop when you call UIApplicationMain function processing touch events, notifications etc. This event loop has its own autorelease pool that autoreleases objects at the end of the loop iteration. This autorelease pool has nothing to do with the autorelease pool you see in main function.
My last question is that whether with ARC or without it, if we had a declared pointer variable inside a method, does the object gets released/destroyed when the method returns/exit?
If you use ARC the objects will be released (unless you return a reference to an object from the method). In MMR you would need to manually send release message to destroy the objects.

Proper retention of object using NSObject load method

I'm not quite sure where I'm going wrong with this implementation and what adjustment I need to make so that the loaded singleton stays in memory.
#implementation ApplicationSettings
static ApplicationSettings *sharedSettings = nil;
+ (void)load
{
#autoreleasepool {
sharedSettings = [self sharedSettings];
[self configureInitialSettings];
}
}
+ (ApplicationSettings*) sharedSettings {
if (sharedSettings)
return sharedSettings;
else {
return [[[ApplicationSettings alloc] init] autorelease];
}
}
- (void) dealloc {
[super dealloc];
}
The main methods for loading are shown here, along with the dealloc (I'm not using ARC).
I have started using this pattern recently. I'm going to have to check each implementation to make sure it's right. I found one case where it is being deallocated and causing a crash. Obviously the #autoreleasepool owns it. Should I remove the autorelease in the return statement so it doesn't go into the autorelease pool? If I do that, then it's retained until the program is killed, which is fine with me. Is there anything wrong with that?
That's not the correct way to declare a singleton class. (And as a result, your +load method and object retention does not fit with your usage here, and the reason of your crash)
Loading the singleton instance in the +load method is useless, as it is best to allocate the instance only when needed, that is when it is first requested (lazy loading)
But more important, returning an autoreleased instance in the sharedSettings method make the singleton pattern invalid and fail its purpose, as you return an instance that will be released as soon as the autorelease pool will be drained (that is at the end of the current RunLoop iteration -- if not sooner if you have any inner #autoreleasepool used). That's very likely to be the cause of your crash!
The implementation of dealloc is useless, first because it only call its super implementation (so you can avoid the whole method definition), and because as your class is meant to be a singleton, the instance will never be released from memory while your app is alive.
And last but not least, your implementation is not thread-safe at all.
Of course, normally you need to balance alloc and init calls with release or autorelease calls. That's the main rule of memory management. But for the Singleton Pattern, as per definition the shared instance of a singleton lives as long as the application live (that's is main role), this is the exception to the rule, and you should not release your sharedInstance that holds your singleton object, to make sure it keeps living and is not deallocated from memory.
One correct (legacy) implementation for a singleton without ARC would be to overload the alloc/retain/release/autorelease/retainCount methods, as explained in the Apple documentation about singleton. But in fact that's not really the way we do it anymore these days, as this documentation is quite old (was written before GCD existed) and obsolete, and as GCD now offers a way better alternative, that is guarantied to be thread-safe, and is compatible with both non-ARC and ARC too (whereas the latter is not possible to implement under ARC environment). So here it goes:
#implementation ApplicationSettings
+(ApplicationSettings*)sharedInstance
{
static ApplicationSettings* sharedInstance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; });
return sharedInstance;
}
#end
And that's all. No need for a global variable outside of the method or whatsoever. Simply declare this method and use it every time you need access to the singleton and you're done.
And if you need to fill some instance variables of your singleton then, like what you probably do in your configureInitialSettings method, simply do it in the init method of your singleton, as you would do in a standard class as usual.
Additional Note: If you want to be really strict, some may argue that it will not forbid the allocation/creation of other instances of the class using alloc/init (and neither do your own implementation in your question) so that is not a real singleton: one can still allocate multiple instances of it if s/he really wants to.
But in practice even if that's true, I don't see any reason why to really add these constraints (and if you switch to ARC one day, you can't add these constraints anyway). What you really want when you seek for the Singleton Pattern is more "a common instance shared accross the whole application" than "a way to forbid the creation of multiple instances", and that's what we have here. And actually that's the case for most of the classes that claim to be Singletons (like NSFileManager for example).

Resources