handling the singleton object - iphone

Sorry to ask basic and some what more important tricky question.I have a singleton class which is already existed in my application( unfortunately i didn't implemented that class).Now i am checking the whole code of the project using the analyzer singleton class showing me the memory leak.I am not sure the code is correct or not because handle singleton class is very tricky.Please any one suggest me why analyzer giving me leak.I attached the singleton class methods please check in the screenshot
In my project we are calling [className sharedDataSource]; many times.Please provide me some knowledge on this Thanks in advance.

I think its quite safe to ignore that warning really.. For more explanation of how the singleton really behaves as a singleton, you may find this link pretty illuminating.
Long story short, all calls to alloc, in turn call allocwithzone, and in this allocwithzone, there is a condition that makes sure that the alloc happens only once. Agreed, the implementation is quite wonky. However there are quite a few different ways to implement a singleton, as evidenced here, if you feel like refactoring it later or may be even just for academic interest.

I think this is correct. Think about it in terms of what a singleton does. A singleton is a class that lives and there is only a single instance for the entire application. It is a purposeful memory leak. That class is declared and is not supposed be released so that it is available later.
If you use this pattern in objective-c, I think you are responsible for clearing the memory when the singleton is no longer needed.

Related

I have made a class and that class has 100 static methods

I want to ask that i made a class which has more than 100 static methods. But class is not static, so i want to ask that do all methods live in application memory whole time or not. Or it is bad programming. please suggest me.
Please solve my issue.
Does it have any non-static method also?
if No, class should be made static.
if yes, i'll say design can be improved.
And all methods are loaded into application memory as soon as class is first used. however only one copy of methods are kept in memory.
If you really want these programs available in a reusable context, then write them as regular external C or C++ functions and add them to a library to use in other projects. Then reintroduce or wrap them as needed. I know - it's not a popular answer among objc devs, but at least it scales much better when you begin to have really complex codebases.
But class is not static, so i want to ask that do all methods live in application memory whole time or not.
Yes, and these methods may not be stripped. When you use these in other projects, you pay for everything. With functions, they may be stripped and you only pay for what you actually use in the program. Specifically, the memory of a function or method exists in the binary and in the program's memory only once - instances do not clone methods, they are referenced and looked up using a dispatch table in the runtime (like a vtable). Each instance of the class only accesses its selectors via this table so method count does not make an instance larger. Memory in this case is rarely (if ever) a concern.
Or it is bad programming. please suggest me.
This is very unusual, and an indication that something has gone wrong in the design.

Helper classes/libraries to make use of KVC/KVO on iOS more practical/safe?

This question is really looking for a specific class that I know exists, but cannot find.
A few weeks ago I read through an article outlining a helper class for using KVC - it let you encapsulate KVC subscriptions so that you could have multiple values being observed without having to go through the same hander method, and also made cleanup of the KVC observers safer (since KVC cleanup is really finicky and exception prone).
So, in responses I am looking for either that helper class I had run across before, or other examples of attempts to wrap KVC to make it safer and more palatable for general use.
I finally found what I was looking for, the key to searching was to look for examples of using KVO with blocks.
I found three interesting resources, which I'll present as a starting point - if anyone has others that are good please also answer.
The first link is the article I mentioned finding before. It has a great summary of the problems with KVO as it stands, and an interesting helper class that encapsulates a KVO session:
http://www.mikeash.com/pyblog/key-value-observing-done-right.html
The second is a simpler NSObject category that lets you pass in a block to be activated on a change notification:
http://blog.andymatuschak.org/post/156229939/kvo-blocks-block-callbacks-for-cocoa-observers
The last is another category on NSObject that uses a binding mechanism to add observation:
http://wirestorm.net/blog/2011/05/27/block-based-observation-with-kvo/
A more up-to-date implementation is facebook kvo implementation using block
It added a NSObject Category to add a KVOController property on all objects. But then we should be more careful about the retain cycles problem.

Alternative to Singleton in Objective-C for better application design

It seems a lot of Objective-C code is using Singleton nowadays.
While a lot of people complaining about Singleton, e.g. Google (Where Have All the Singletons Gone?), their fellow engineers also use it anyway: http://code.google.com/mobile/analytics/docs/iphone/
I know we had some answers in Stack Overflow already but they are not totally specific to Objective-C as a dynamic language: Objective C has categories, while many other languages do not.
So what is your opinion? Do you still use Singleton? If so, how do you make your app more testable?
Updated: I think we need to use codes as example for more concrete discussion, so much discussions on SO are theory based without a single line of code
Let's use the Google Analytics iOS SDK as an example:
// Initialization
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-0000000-1"
dispatchPeriod:kGANDispatchPeriodSec
delegate:nil];
// Track page view
[[GANTracker sharedTracker] trackPageview:#"/app_entry_point"
withError:&error];
The beauty of the above code is once you have initialized using the method "startTrackerWithAccountID", you can run method "trackPageview" throughout out your apps without passing through configurations.
If you think Singleton is bad, can you improve the above code?
Much thanked for your input, have a happy Friday.
This post is likely to be downvote-bait, but I don't really understand why singletons get no love. They're perfectly valid, you just have to understand what they're useful for.
In iOS development, you have one and only one instance of the application you currently are. You're only one application, right? You're not two or zero applications, are you? So the framework provides you with a UIApplication singleton through which to get at application-level os and framework features. It models something appropriately to have that be a singleton.
If you've got data fields of which there can and should be only one, and you need to get to them from all over the place in your app, there's totally nothing wrong with modeling that as a singleton too. Creating a singleton as a globals bucket is probably a misuse of the pattern, and I think that's probably what most people object to about them. But if you're modeling something that has "singleness" to it, a singleton might well be the way to go.
Some developers seem to have a fundamental disgust for singletons, but when actually asked why, they mumble something about globals and namespaces and aesthetics. Which I guess I can understand, if you've really resolved once and for all that Singletons are an anti-pattern and to be abhorred in all cases. But you're not thinking anymore, at that point. And the framework design disagrees with you.
I think most developers go through the Singleton phase, where you have everything you need at your fingertips, in a bunch of wonderful Singletons.
Then you discover that unit testing with Singletons can be difficult. You don't actually want to connect to the database, but your Singleton does. Add a layer of redirection and mock it.
Then you discover that unit testing isn't the only time you need different behaviour. You make your Singleton configurable to have different behaviour based on a parameter. You start to wonder if you need to split it into two Singletons. Then your code needs to know which Singleton to use, so you need a Singleton that knows which Singleton to use.
Then some other code starts messing with the values in your Singleton, while you're using it. How dare they! If you wanted just anybody to get at those values from anywhere, you'd make them global...
Once you get to this point, you start wondering if Singletons were the right solution. You start to see the dangers of global data, particularly within an OO design, where you just assume your data won't get poked at by other people.
So you go back and start passing the data along, rather than looking it up (this used to be called good OO design, but now it has a fancy name like "Dependency Injection").
Eventually you learn that Singletons are fine in moderation. You learn to recognize when your Singleton needs to stop being single.
So you get shared objects like UIApplication and NSUserDefaults. Those are good uses of Singletons.
I got burned enough in the Java Singleton craze a decade ago. I don't even consider writing my own Singletons. The only time I've needed anything similar in recent memory is wanting to cache the result of [NSCalendar currentCalendar] (which takes a long time). I created a category on NSCalendar and cached it as a static variable. I felt a bit dirty, but the alternative was painfully slow code.
To summarize and for those who tl;dr:
Singletons are a tool. They're not likely to be the right tool, but you have to discover that for yourself.
Why do you need an answer that is "total Objective C specific"? Singletons aren't totally Obj-C specific either, and you're able to use those. Functions aren't Obj-C-specific, integers aren't Obj-C specific, and yet you're able to use all of those in your Obj-C code.
The obvious replacements for a singleton work in any language.
A singleton is a badly-designed global.
So the simplest replacement is to just make it a regular global, without the silly "one instance only" restriction.
A more thorough solution is, instead of having a globally accessible object at all, pass it as a parameter to the functions that need it.
And finally, you can go for a hybrid solution using a Dependency Injection framework.
The problem with singletons is that they can lead to tight coupling. Let's say you're building an airline booking system: your booking controller might use an
id<FlightsClient>
A common way to obtain it within the controller would be as follows:
_flightsClient = [FlightsClient sharedInstance];
Drawbacks:
It becomes difficult to test a class in isolation.
If you want to change the flight client for another implementation, its necessary to search through the application and swap it out one by one.
If there's a case where the application should use a different implementation (eg OnlineFlightClient, OfflineFlightClient), things get tricky.
A good workaround is to apply the dependency injection design pattern.
Think of dependency injectionas telling an architectural story. When the key actors in your application are pulled up into an assembly, then the application’s configuration is correctly modularized (removing duplication). Having created this script, its now easy to reconfigure or swap one actor for another.”. In this way we need not understand all of a problem at once, its easy to evolve our app’s design as the requirements evolve.
Here's a dependency injection library: https://github.com/typhoon-framework/Typhoon

reachability and singleton

How can I make the reachability work as a singleton?
Here is what I want to do ...
I have an application.
When it launches I want to have a singleton and work with the reachability in order to hold the network status.
Then I want from other controllers to access the singleton and check the network status.
For example I want every time user clicks on one tab and the screen is shown to check the internet status and enable or disable a button.
I know the question is very generic but I am so confused.
I am currently using reachability 2.2
Any tips or ideas or even guides will be appreciated.
And a final question....
how 'moral' is the singleton usage? And is it the best practice to be more close to MVC model?
Thanks again
Singletons are fine. Reachability can be a very sensible singleton. You should be aware of the doc "Creating a Singleton Instance" in Apple's Cocoa Fundamentals Guide, but read the text carefully. The code they present is seldom what you need and can cause more problems then it solves. It is only appropriate in cases where it is wrong for there to be multiple copies of the object (wrong because the object manages a unique resource for instance). In those cases, I tend to prefer asserting in -init rather than overloading allocWithZone: because I'd rather force the developer to make the correct call (+sharedInstance) rather than quietly fix it for them, and have them think they've created two instances when there is actually one (at least in cases where the singleton is mutable or holds state).
There is an excellent discussion of good singleton patterns in this question. I favor #Robbie Hanson's answer in my own code because it is cheaply thread-safe.

Is it generally faster to call an instance method rather than a class method?

Today I encountered something strange: I tried to put a utility method into an Utility class as a class method, so that I can simply call that method to generate me an convenient UIView with no hassle (not the imageNamed method but the other, much more complex one). It was horrible. The performance was so incredible bad. Then I made an instance method out of it, created an instance of that class and called the instance method. Performance was suddenly great. That is so strange!
What are your experiences with this kind of stuff?
There's something else going on in your case. Method calls are pretty lightweight, and I doubt there is a noticeable difference in performance between a class method and an instance method. At least, I've never seen a difference between the two in my experience.
Sources of performance degradation are often not what they first appear to be, so I recommend running your application against Instruments or Shark to see where the bottleneck is in this case. My guess is that you are allocating memory in the class method approach that was not allocated in the instance method, which is one of the most expensive operations on the iPhone.