Memory leaking problem in iphone app - iphone

i created one method like below one:
+ (JSONManager *)GetInstance
{
if (!instance)
{
instance = [[JSONManager alloc] init];
}
return instance;
}
and i need to use same method in different view...if i release this one for the first view it is working fine and if trying to navigate to second view my app is crashing.
can any one please let me know where do i need to release that object
Thanks in advance

This appears to be a singleton. You should not be releasing it in the first view. You will want to use the same instance throughout the lifetime of the application.
If that is not the requirement, you should provide the mechanism to set the instance variable to nil as it will be pointing to a deallocated object once you release it. But I think this is not the case.

If you want a true singleton use this template and generate it.
It's based on Apple's Singleton code
http://blog.mugunthkumar.com/coding/objective-c-singleton-template-for-xcode-4/

The code looks like a Singleton. The purpose of Singleton is to have a single instance of a resource available throughout an app.
So, you should not release the instance, after you are done with it in the first view, since you want to use it in another view.
If you are worried about releasing this instance have a look at the following link for a template singleton class for an iOS application:
http://www.galloway.me.uk/tutorials/singleton-classes/

Related

How to ensure that all the UIViewController objects in the project are being created only once?

In the project i am currently working upon, there are lots and lots of UIViewController objects (of some UIViewController subclass) are created and used. And believe me it was creating lots of issues. And I am working upon it (kind of refactoring).
As I see, most of the (those)objects required initialization only once and used multiple times. As I will be working on this project from now (and also the project is of long duration), How can I be sure that each of the UIViewController Subclass object is only one alive at a time.
I doubt if I should make all the UIViewControllers Singleton. And if so, How should I implement that. Meaning; Should I initialize all the objects in applicationDidFinishedLaunching:WithOptions or where?
Another Question is: (As I think might not be true) Should all the UIViewController in project be singleton?
If you want to ensure that all the UIViewController objects in the project are being created only once then only way is Singleton. And you need not to intialize them in applicationDidFinishLaunching. You can intialize them any where(usually where you need them).
Go to link for creating singleton properly: http://cocoasamurai.blogspot.in/2011/04/singletons-your-doing-them-wrong.html
Source : Make UIViewController a singleton?
Well making them singleton if you want them to be only one object of each subclass is not a bad idea,
if you made them singletons, don't initialize them in applicationDidFinishedLaunching:WithOptions but initialize them as soon as you need them (read more about lazy initialization)
However i would suggest to make each webView a property of your Appdelegate, such that whenever you need them you will get them from the appDelegate

Instances of Objects in Objective-C - iPhone/iPad

I am developing an iOS app that is a calculator to keep track of a score of a certain game. The game has many view controllers. I am going to create a "Player" object and create 4 instances of that player. Now in terms of Objective-C, how would I keep those instances alive between several view controllers? Should I for example, create an array of players and keep passing the array from one VC to another as the view progresses?
Thank you,
using singleton class , you will get the anywhere the same object. you need not to create each and every time. it create once and you use the app whole.
You can create the 4 instances in AppDelegate.
Then these 4 instances will be accessible by all view controller using shared AppDelegate object.
Let me know in case of any difficulty.
Cheers.
Just a quick thought, Passing array of Players can resolve your problem. But quickest way to share objects between view controllers is through using Application Delegate as you can simply access application delegate anywhere.
you can use of ApplicationDelegate to store your progress. when you move to another view at that time update your ApplicationDelegate variable in - (void) viewWillDisappear:(BOOL)animated method and at another view in viewLoad method get the updated value from the delegate variable.

Why is everything a property in iOS SDK tutorials?

In most of the iOS SDK tutorials I've read online both from Apple and elsewhere, so many instance variables are made properties, even when they are only accessed from within their own class.
E.G. in Facebook's latest iOS SDK a user is encouraged to maintain an instance of the Facebook class called facebook in the app delegate. facebook" is a property. This is then referred to throughout the sample code as "self.facebook". But the "facebook" property is not referenced anywhere from outside the app delegate.
Why is this? What am I missing? If an instance variable is only used within its own class, my inclination would be not to make it a property so that it is not publicly visible, and refer to it simply as facebook rather than self.facebook or self->facebook from within the class.
Frankly, even if I needed the facebook property, I think I'd rather refer to it within the app delegate as simply "facebook" rather than "self.facebook".
So what gives? Why am I seeing properties everywhere?
Properties don't have anything to do with whether an iVar is publicly exposed or not. Instead properties create accessors methods that manage retention and foster encapsulation.
If you want a private property just declare the ivar under the #private directive and then define the properties in the implementation file.
One great example of why you should use properties (you can make properties private as TechZen noted), is creating new instances in viewDidLoad.
People do this all the time, because it's called once per instance of a view controller. Or, so you think... in reality because of what happens when you application gets a memory warning, a viewDidLoad class could be called multiple times per instance.
So for example you might well write code like:
- (void) viewDidLoad
{ myArray = [[NSMutableArray alloc] init]; }
Works great - until it's called again, then you have a leak. You could release myArray before you assign it just in case - but the trouble is that's an easy step to forget.
If you use properties for every instance variable though, then your code looks like this:
- (void) viewDidLoad
{ self.myArray = [NSMutableArray array]; }
Now you can't get it wrong. If viewDidLoad is called multiple times, the old array will be released and a new one will go in its place, without leaking the old array.
Usually it's better to access to the instance variable through an accessor, rather than directly. Properties create these accessors, and also provide things like proper key-value change notifications and atomic access.
Properties can generate getters and setters. Setters, in particular, can help manage retain/release counts of objects (semi)automatically, and thus reduce certain types of potential memory bugs.
Getters and properties for non-objects are mostly for orthogonality of coding style, although they do have potential to be used for mutators, key-value notifications, etc. in some future extension or reuse of the code.
There may be some efficiency differences/disadvantages, but that depends on the particular ObjC run-time in use.
if you refer to facebook, then it will access the variable directly, if you access self.facebook, then it will go through the setter/getter methods.
the result is that if you need to mutate an object or at somepoint later in time, you need to do other things during the process of changing the value(ie boxing it) then you can put this in the setter method and reduce having to do it everywhere. its a good thing.
It creates the getter/setter for you automatically.
Also, here is a good post explaining it properties

What's an effective CoreData context/coordinator strategy for this common application pattern?

I have a common application pattern: user enters data in the main view controller, then views it in a table in a modal view controller, where rows can be deleted or modified. I was following the general design strategy from the Stanford iPhone course, but somewhere things went off the rails and all I've been getting is SIGABRT's and exceptions like "Illegal attempt to establish a relationship 'xyz' between objects in different contexts."
As in the Stanford course, I use a singleton class called "Database" which should return the same context whenever requested. So the first commands in my viewDidLoad method on the main view controller are:
dbsingleton = [Database sharedInstance];
nmocontext = [dbsingleton managedObjectContext];
nmocontext is an ivar I use throughout the view controller. When the user wants to see the other view controller, with the table, I alloc-init it, then present it modally. (It has an NSFetchedResultsController that supplies the data from my store.) I've tried various strategies here:
I've made the NSFetchedResultsController a retained property set by the main view controller
I've made the NSManagedObjectContext a retained property set by the main view controller; and
I've used the singleton internally by repeating those two lines of code above at the beginning of the table view controller's viewDidLoad method.
Whichever I go with, the one problem I just can't solve is that after the user closes and deallocs the table view controller (and its NSFetchedResultsController), I start getting crashes in the main view controller when the store is accessed (like the "Illegal attempt" error mentioned above).
What are best practices for dealing with this common application pattern? I am still hoping to make this application iPhone SDK 3.x compatible, but I do seem to have fewer crashes when I'm using iOS 4 -- if there are underlying issues with 3.x that are causing me problems, please let me know and I may target iOS 4 only.
Thank you!
This is just a guess but I assume the following problem for your crashes after closing the tableview:
You declared a property
#property (retain, nonatomic) NSManagedObjectContext* nmocontext;
do you properly release the ivar nmocontext in dealloc?
If yes your problem is the assignment
nmocontext = [dbsingleton managedObjectContext];
This never retains nmocontext within your viewcontroller but you release it on dealloc.
Second:
"Illegal attempt to establish a relationship 'xyz' between objects in different contexts."
This is not a memory management issue, but you probably created another new context to add objects (like in the apple core data iphone samples) and tried to set a NSManagedObject as relationship from a different context.
It sounds like you don't have your singleton properly configured.
A singleton should override release to do nothing such that when it is sent a release message nothing happens. If you do not override release then any random piece of code anywhere in the app can kill the singleton and defeat the entire purpose of using a singleton. The next time you call singleton, you actually get another new object which in this case also returns a new managed object context.
See Cocoa Fundamentals Guide: Creating a Singleton Instance.
Singletons are powerful and flexible but very easy to do wrong. They are so easy to screw up that many experienced developers simply refuse to use them. If don't have experience with them, don't use them when you are just starting out.

Passing a float between multiple viewcontrollers

Im using tabs to switch between two view controllers.
How do I retrieve a float in the secondviewcontroller, thats been initiated in the firstviewcontroller? should i make some sort of global variable? Where and how do I do this?
Thanks guys :)
Global variables are never desirable, I would strongly recommend using some messaging pattern, s.th. SecondViewController and FirstViewController can synchronize whenever they change anything of interest to the other.
On first glance, I only found this guideline http://www.informit.com/articles/article.aspx?p=1398611 telling about messaging-patterns in cocoa, I guess there will already be sample-implementations for iPhone floating around.
You could make that variable a property of your app delegate, which would be accessible from anywhere within your app. If you don't want that for whatever reason, you could create a "helper" singleton to keep such variables and make them properties again.
Use AppDelegate For This
+(BOOL)SetData:(float)Value
{
GlobalValue=Value;
}
+(float)ReturnData
{
return GlobalValue;
}
and Call like This
[YourAppDelegate ReturnData];