views:

71

answers:

2

Hi,

I'm new in iPhone developement and I have a EXC_BAD_ACCESS error.

In my .h I declare:

NSString *myString;

In my .m I have to methods:

. The (void)locationManager of CLLocationManager interface when I do it:

myString = [NSString stringWithFormat:@"%lf",loc.longitude];
NSLog(@"%@",myString); // it works

. A (void)sendPosition method with:

NSLog(@"%@",myString); // EXC_BAD_ACCESS

Can you help me?

Thanks a lot

A: 

Are you retaining myString somewhere else in your locationManager method? If not, you should, then release it in your -dealloc method. Otherwise, it could disappear like I suspect is what's happening now. Please read up on the rules for memory management.

What I would recommend is creating a property which retains the value automatically on your class, then assign it with the dot notation when you create the string. Again, releasing it in your dealloc method. This is idiomatic these days for this type of code.

jer
+1  A: 
  1. Retain your string.

    myString = [[NSString stringWithFormat:@"%lf",loc.longitude] retain];

  2. Then in your dealloc method of this class (or add it)

    -(void) dealloc{ [super dealloc]; [myString release]; }

that should fix it, assuming you have declared myString in you .h file.

John Ballinger
This is because an NSString is autoreleased, and will need to be retained if you want it to hang around. Alternatively, you could make it a property that is retained and not have to call retain (note you will still have to release it in dealloc)
jrtc27
Thanks, it works, but value of myString could change regulary. With retain, the value is always the same.
Alex R.
If your value can change, use a mutable string, and just change the value. Otherwise, release it and set it again when you create a new value. Seriously, look at my answer, read up on the rules (you need to know them), and when you run into issues like this, stop and think. There's usually a simple solution.
jer
Thanks for help, I'm beginner in Objective-c language and It's very different of others languages like php or Java. I don't know all types of attributes. It doesn't work very well but I'll follow your advice, I'll search alone. Thanks again.
Alex R.