MKMapView removeAnnotations cause memory leak - iphone

everyone!
I have tested this simplest code as following:
StorePin.h
#import <Foundation/Foundation.h>
#import <MAPKIT/mapkit.h>
#import <CORELOCATION/corelocation.h>
#interface StorePin : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *subtitle;
NSString *title;
}
#property (nonatomic,assign) CLLocationCoordinate2D coordinate;
#property (nonatomic,retain) NSString *subtitle;
#property (nonatomic,retain) NSString *title;
-(id) initWithCoords:(CLLocationCoordinate2D) coords;
#end
StorePin.m
#import "StorePin.h"
#implementation StorePin
#synthesize coordinate, subtitle, title;
- (id) initWithCoords:(CLLocationCoordinate2D) coords{
self = [super init];
if (self != nil) {
coordinate = coords;
}
return self;
}
- (void) dealloc
{
[title release];
[subtitle release];
[super dealloc];
}
#end
In my ViewControlller, I made a button to add and remove annotations repeatly.
#import "mapViewTestViewController.h"
#import "StorePin.h"
#implementation mapViewTestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)refresh
{
[mapView removeAnnotations:mapView.annotations];
for (int i = 0; i < 101; i ++)
{
CLLocationCoordinate2D p1;
p1.latitude = i/10.0;
p1.longitude = i/10.0;
StorePin *poi = [[StorePin alloc] initWithCoords:p1];
[mapView addAnnotation:poi];
[poi release];
}
}
- (void)dealloc
{
[super dealloc];
}
#end
If I loop less than 100 times to add and remove annotations, all work normally. But if I loop more than 100 times, it will cause memory leak once. I'm nearly crazy to this strange problem. Is this my code's bug or mkmapview's bug? Thank you for helping me.

You don't say what objects have been detected as leaking, but if they are StorePins, then it's MapKit's problem -- your memory management code for the StorePins you create in the loop is just fine.
One thing that you do that might be causing MapKit trouble is passing the map view a reference to its own ivar that you want it to modify. It doesn't seem too likely -- if it was really a problem, it would probably cause a crash rather than a leak. However, you might try making a copy, either shallow (as Kai wrote earlier, but absolutely do not follow the advice about using retain counts and calling release in a loop):
NSArray * annotationsCopy = [NSArray arrayWithArray:mapView.annotations];
or deep:
NSArray * annotationsDeepCopy = [[[NSArray alloc] initWithArray:mapView.annotations
copyItems:YES]
autorelease];
then pass the copy to removeAnnotations:.
The second option creates an autoreleased array with a copy of every item in the annotations list so that the map view doesn't try to remove the same instances that it's iterating over. Obviously this uses twice the memory; you probably only want to bother with this for bug-hunting.
If it fixes the leak, great, if not, then there's probably nothing you can do about it.

In case you don't want to remove the user's location blue dot on the map, you can use:
NSArray * annotationsCopy = [NSArray arrayWithArray:[mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"!(self isKindOfClass: %#)", [MKUserLocation class]]]];

Related

NSMutableArray with memory leak

I am using following code to create NSMutableArray. When I run the same in “Profile” mode, it is showing a memory leakage.
SampleArray.h
#interface SampleArray: NSObject {
}
#property (assign, retain) NSMutableArray *array;
#end
SampleArray.m
#import "SampleArray.h"
#implementation SampleArray
#synthesize array;
-(void) viewDidLoad {
self.array =[ [NSMutableArray alloc] init];
}
-(void) viewWillDisappear:(BOOL)animated {
[self.array release];
}
#end
When I am using autorelease, then I can’t able to access the same in other function or method and return null value. Please help me to find the issue.
releasing this array in viewWilLDisappear is not a good idea, you should release in the dealloc function. You should worry about over-releasing this item and causing a program crash since viewWilLDisappear may get called multiple times during the lifetime of this ViewController.
Anyhow, you are double retaining the item beacuse your property has a retain on it (and make it nonatomic, not assign), add an autorelease to your alloc/init:
self.array =[[[NSMutableArray alloc] init] autorelease];
and move
[array release];
to your dealloc function. Or convert to ARC and don't worry any longer...
Try setting it to (nonatomic, retain), then autoreleasing.
It is better to handle memory de-allocation in your -dealloc() and set your array to nil to be more secure in your -viewDidUnload()
so it will be:
-(void) viewDidUnload
{
self.array = nil;
}
-(void) dealloc
{
[array release];
[super dealloc];
}
and like other people said, declare your property as (nonatomic, retain) instead of (assign, retain)
First of all I'm assuming that you are using
#property (nonatomic, retain) NSMutableArray *array;
use this
-(void) viewDidLoad {
array =[[NSMutableArray alloc] init];
}
-(void) viewWillDisappear:(BOOL)animated {
[array release];
}
I will recommend you to use dealloc instead of viewWillDisappear
-(void) dealloc {
[array release];
[super dealloc];
}
Explanation of your code
-(void) viewDidLoad {
// here you are allocating a mutable array thus retain count becomes one
// then you are assigning it to the property which is retain and thus retains it
// making the retain count 2
self.array =[ [NSMutableArray alloc] init];
}
-(void) viewWillDisappear:(BOOL)animated {
// here you are releasing it so its retain count becomes 1 from 2
// thus shows memory leak
[self.array release];
}

MKMapView - Removing annotation causes app crash

Removing annotations from my map view in the following way:
if ([[self.mapView annotations] count] > 0)
{
[self.mapView removeAnnotations:[self.mapView annotations]];
}
causes my application to crash with the following exception:
*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <MKAnnotationContainerView 0xe87b420> for the key path "title" from <PFAnnotation 0x10851230> because it is not registered as an observer.'
The annotations are added in the following way:
CLLocationCoordinate2D pinPosition;
for (int index = 0; index < [array count]; index++)
{
Station *aStation = [array objectAtIndex:index];
PFAnnotation *stationPin = [[PFAnnotation alloc] init]; //StationPinView
pinPosition = CLLocationCoordinate2DMake([[aStation valueForKey:#"latitude"] doubleValue], [[aStation valueForKey:#"longitude"] doubleValue]);
stationPin.stationName = [aStation valueForKey:#"stationName"];
stationPin.stationPosition = pinPosition;
stationPin.stationLength = [aStation valueForKey:#"platformLength"];
[self.mapView addAnnotation:stationPin];
[stationPin release];
}
My PFAnnotation.h is:
#interface PFAnnotation : NSObject <MKAnnotation>
{
NSString *stationName;
CLLocationCoordinate2D stationPosition;
NSNumber *stationLength;
}
#property (nonatomic, retain) NSString *stationName;
#property CLLocationCoordinate2D stationPosition;
#property (nonatomic, retain) NSNumber *stationLength;
#end
and my PFAnnotation.m is:
#implementation PFAnnotation
#synthesize stationName;
#synthesize stationPosition;
#synthesize stationLength;
- (CLLocationCoordinate2D)coordinate;
{
return stationPosition;
}
- (NSString *)title
{
return stationName;
}
- (NSString *)subtitle
{
if (stationLength == nil)
return nil;
else
return [NSString stringWithFormat:#"Platform Length: %#ft",stationLength];
}
- (void)dealloc {
[stationName release];
[stationLength release];
[super dealloc];
}
I have read in some other threads that, setting the annotation properties from background thread is the reason for the above error. But in my case,it is not so because every thing is performed on the main thread. Please advise.
ok..solved it at last!!! I think it was due to the animation provided during addition of annotations. since there were a number of annotations that were added back-to-back with animation and also the annotations were removed just before the animation started, there could have been a reference to the released annotation(this is my guess). Moreover, the removal+addition process was made on each regionDidChangeAnimated call, which could have made a overlap between the removal and addition process. Anyway, how I solved it was that, I provided a timer which will be fired only after 1 second after every regionDidchangeAnimated to make sure that the user has done with dragging. Thus unnecessary addition+removal of annotations was avoided and I was able to avoid the crash. Thanks to all guys here for their time taken to support me, especially Guntis Treulands.
In your PFAnnotation class, did you declare both title and subtitle properties as they are in the protocol?
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKAnnotation_Protocol/Reference/Reference.html
If Your PFAnnotation really has incorrect setters getters for string values:
from here: http://cocoadevcentral.com/d/learn_objectivec/
Setter:
- (void) setCaption: (NSString*)input
{
[caption autorelease];
caption = [input retain];
}
Getter:
- (NSString*) caption
{
return caption;
}
Release:
- (void) dealloc
{
[caption release];
[super dealloc];
}
also - it's easier to provide coordinates in this way: (also works on ios 3.1.3)
stationPin.stationPosition = (CLLocationCoordinate2D) {[[aStation valueForKey:#"latitude"] doubleValue], [[aStation valueForKey:#"longitude"] doubleValue]}
than (only from ios 4)
stationPin.stationPosition = CLLocationCoordinate2DMake([[aStation valueForKey:#"latitude"] doubleValue], [[aStation valueForKey:#"longitude"] doubleValue]);
Please check whether an explicit removal of observer to the property "title" is being done anywhere in the code.

Unrecognized selector sent to instance?

I have seen that a few others have had this problem as well.
I'm trying to follow a tutorial online that shows how to create animated pins on a MapView.
I have implemented the code as shown in the tutorial and the project builds fine except I receive this exception:
-[MKPointAnnotation iconN]: unrecognized selector sent to instance
I have a subclass of 'MKPinAnnotationView' and in the .m file I create this method:
- (void)setAnnotation:(id<MKAnnotation>)annotation {
[super setAnnotation:annotation];
//Place *place = [[Place alloc] init];
Place *place = (Place *)annotation;
//The following line is where the program sends "SIGABRT"
icon = [UIImage imageNamed:[NSString stringWithFormat:#"pin_%d.png", [place.iconN intValue]]];
[iconView setImage:icon];
}
Here are a few parts from my "model" which is called Place.h/.m.
Here is where I create the property for 'iconN'.
#property (retain, nonatomic) NSNumber *iconN;
And here I synthesize it:
#synthesize iconN = _iconN;
Any help is greatly appreciated.
EDIT:
Here is the Place.h and Place.m
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface Place : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
}
#property (retain, nonatomic) NSNumber *iconN;
#property (nonatomic, copy) NSString *title;
#property (nonatomic) CLLocationCoordinate2D coordinate;
- (id)initWithLong:(CGFloat)lon Lat:(CGFloat)lat iconNumber:(NSNumber *)iconNumber;
#end
And the Place.m
#import "Place.h"
#implementation Place
#synthesize coordinate;
#synthesize iconN = _iconN;
#synthesize title;
- (id)initWithLong:(CGFloat)lon Lat:(CGFloat)lat iconNumber:(NSNumber *)iconNumber {
self = [super init];
if (self) {
coordinate = CLLocationCoordinate2DMake(lat, lon);
self.iconN = iconNumber;
}
return self;
}
- (NSString *)title {
return [NSString stringWithFormat:#"Bus: %d", [self.iconN intValue]];
}
- (NSString *)subtitle {
return [NSString stringWithFormat:#"bus[%d] from database.", [self.iconN intValue] - 1];
}
#end
You cannot convert a MKAnnotation to a Place just by casting it. This line is wrong.
Place *place = (Place *)annotation;
You should post your Place.h and Place.m files if you're still stuck. You need to either set the iconN property on a new Place object, or create an init method in the Place class that accepts the MKAnnotation object as a parameter and sets it own internal values accordingly.
In the line
Place *place = (Place *)annotation;
has the variable place of annotation variable class (MKPointAnnotation), you are not able to bring the master class variable to a subclass in this way. Instead you'll have to make a constructor for Place from MKPointAnnotation and perform a check in the setAnnotation method that annotation is of MKPointAnnotation.
You are sending the message to the annotation but you seem to have subclasses the annotation view.
Posting as an answer what was originally just a comment:
I'm not familiar with the MapKit, but the thing that sticks out for me in this: -[MKPointAnnotation iconN]: unrecognized selector sent to instance is that the class is MKPointAnnotation. So the annotation you're receiving isn't actually a Place object, it's an MKPointAnnotation object - you can't just cast to Place. I suspect the root of your problem is where you create your annotation object in the first place.

Data going missing when passed between threads using a Singleton

Edit:
Thanks #BlackFrog. I think I'm nearer now, but the values are still not get getting through...
The values are set as shown by logs within [progressController updateProgressSummary:...] but are nil when I log them in progressUpdate initWithProgressUpdate:.... as shown below.
I'm slightly confused over which property is used the one set for progressUpdate or the ones set for each of the 3 components of progressUpdate. I have changed the 3 individual properties from assign to retain as suggested and have also tried doing the same with the overall progressUpdate property too (not shown here).
progressController.h
......
#property (nonatomic, assign) ProgressUpdate *progressUpdate;
progressController.m
// Ask delegate to update and display Progress text
-(void) updateProgressSummary:(NSString *)summary detail:(NSString *)detail percentComplete:(NSNumber *)complete {
// These report the proper values
DLog(#"Reporting Summary - %s", [summary UTF8String]);
DLog(#"Reporting Detail - %s", [detail UTF8String]);
DLog(#"Reporting Complete - %i", [complete intValue]);
if (summary != nil)
self.progressUpdate.summaryText = summary;
self.progressUpdate.detailText = detail;
self.progressUpdate.percentComplete = complete;
ProgressUpdate *progressUpdateForIssue = [[ProgressUpdate alloc] initWithProgressUpdate:progressUpdate];
[self.delegate performSelectorOnMainThread:#selector(displayProgress:) withObject:progressUpdateForIssue waitUntilDone:NO];
[progressUpdateForIssue release];
}
But then a few milliseconds later...., inside the object....they're nil.
progressUpdate.h
.....
#property (nonatomic, retain) NSString *summaryText;
#property (nonatomic, retain) NSString *detailText;
#property (nonatomic, retain) NSNumber *percentComplete;
progressUpdate.m
-(id) initWithProgressUpdate:(ProgressUpdate *)update {
if ((self = [super init])) {
summaryText = [update.summaryText copy];
detailText = [update.detailText copy];
percentComplete = [[NSNumber alloc] initWithFloat:[update.percentComplete floatValue]];
}
// These report nil values
DLog(#"Reporting in progUpdate summaryText - %s", [summaryText UTF8String]);
DLog(#"Reporting in progUpdate detailText - %s", [detailText UTF8String]);
DLog(#"Reporting in progUpdate percentComplete - %i", [percentComplete intValue]);
return self;
}
end of update
I need some help with passing data in a custom class from one thread to another. Its there before the pass but then disappears upon arrival. I've tried everything I know, but to no avail.
My background thread calls ProgressController and passes it details of the current progress. That in turn does performSelectorOnMainThread on ProgressController's delegate (the view controller) to display the details.
It was all working fine when I was passing through a single NSString, but I need to pass two strings and a number and as performSelectorOnMainThread can only pass one object, I have encapsulated these in a custom object - ProgressUpdate.
The data gets through to ProgressController correctly but is null by the time that it appears in the View Controller. I know this as I've put NSLogs in various places.
I wonder if its to do with:
multithreading and custom objects
the fact that ProgressController is a singleton, which is why I have then alloc'd a new ProgressUpdate each time its called, but that has not helped.
Any ideas welcome. For clarity, the code is below.
ProgressUpdate.h
#import <Foundation/Foundation.h>
#interface ProgressUpdate : NSObject {
NSString *summaryText;
NSString *detailText;
NSNumber *percentComplete;
}
#property (nonatomic, assign) NSString *summaryText;
#property (nonatomic, assign) NSString *detailText;
#property (nonatomic, assign) NSNumber *percentComplete;
-(id) initWith:(ProgressUpdate *)update;
#end
ProgressUpdate.m
#import "ProgressUpdate.h"
#implementation ProgressUpdate
#synthesize summaryText, detailText, percentComplete;
-(id) initWith:(ProgressUpdate *)update {
self = [super init];
self.summaryText = update.summaryText;
self.detailText = update.detailText;
self.percentComplete = update.percentComplete;
return self;
}
#end
ProgressController.m
static ProgressController *sharedInstance;
+ (ProgressController *)sharedInstance {
#synchronized(self) {
if (!sharedInstance)
[[ProgressController alloc] init];
}
return sharedInstance;
}
+(id)alloc {
#synchronized(self) {
NSAssert(sharedInstance == nil, NSLocalizedString(#"Attempted to allocate a second instance of a singleton ProgressController.", #"Attempted to allocate a second instance of a singleton ProgressController."));
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id) init {
if (self = [super init]) {
[self open];
}
return self;
}
.........
// Ask delegate to update and display Progress text
-(void) updateProgressSummary:(NSString *)summary detail:(NSString *)detail percentComplete:(NSNumber *)complete {
if (summary != nil)
self.progressUpdate.summaryText = summary;
self.progressUpdate.detailText = detail;
self.progressUpdate.percentComplete = complete;
ProgressUpdate *progressUpdateForIssue = [[ProgressUpdate alloc] initWith:progressUpdate];
[self.delegate performSelectorOnMainThread:#selector(displayProgress:) withObject:progressUpdateForIssue waitUntilDone:NO];
[progressUpdateForIssue release];
}
RootViewController.m
// Delegate method to display specific text in Progress label
- (void) displayProgress:(ProgressUpdate *)update {
[progressSummaryLabel setText:update.summaryText];
[progressDetailLabel setText:update.detailText];
[progressBar setProgress:[update.percentComplete intValue]];
[progressView setNeedsDisplay];
}
In the init method, you are only assigning the ivars and not retaining them in the new object.
Redo your init method as the following:
-(id) initWithProgressUpdate:(ProgressUpdate *)update {
if ((self = [super init])) {
summaryText = [update.summaryText copy];
detailText = [update.detailText copy];
percentComplete = [[NSNumber alloc] initWithFloat:[update.percentComplete floatValue];
}
return self;
}
Couple of points:
You should not use accessor in the init method
Rename your init method to be a lot clear
In the #property, change the assign to retain
Try removing the statement '[progressUpdateForIssue release];' in the method
'-(void) updateProgressSummary:(NSString *)summary detail:(NSString *)detail percentComplete:(NSNumber *)complete '.
Also change the property attribute from 'assign' to 'retain' in your class ProgressUpdate.
You could release those properties in the dealloc method .
Good luck.

IS this class Many part of memory Leak

I am much confuse about my class.
Specially about Memory Management.
Please Guide me about NSString Concept at here.
My Class is.
#import <Foundation/Foundation.h>
#interface itinerary_detail : NSObject {
NSString *itinerary_title;
NSString *itinerary_creator;
NSString *itinerary_identifiere;
NSString *itinerary_created;
NSString *itinerary_modified;
}
#property (retain) NSString *itinerary_title;
#property (retain) NSString *itinerary_creator;
#property (retain) NSString *itinerary_identifiere;
#property (retain) NSString *itinerary_created;
#property (retain) NSString *itinerary_modified;
-(void) itinerary_initialization;
-(void) itinerary_title:(NSString *) xml_value;
-(void) itinerary_creator:(NSString *) xml_value;
-(void) itinerary_identifiere:(NSString *) xml_value;
-(void) itinerary_created:(NSString *) xml_value;
-(void) itinerary_modified:(NSString *) xml_value;
#end
and My .m class is
#import "itinerary_detail.h"
#implementation itinerary_detail
#synthesize itinerary_title,itinerary_creator,itinerary_identifiere,itinerary_created,itinerary_modified;
-(void) itinerary_initialization
{
itinerary_title=#"null";
itinerary_creator=#"null";
itinerary_identifiere=#"null";
itinerary_created=#"null";
itinerary_modified=#"null";
}
-(void) itinerary_title:(NSString *) xml_value
{
itinerary_title=xml_value;
}
-(void) itinerary_creator:(NSString *) xml_value
{
itinerary_creator=xml_value;
}
-(void) itinerary_identifiere:(NSString *) xml_value
{
itinerary_identifiere=xml_value;
}
-(void) itinerary_created:(NSString *) xml_value
{
itinerary_created=xml_value;
}
-(void) itinerary_modified:(NSString *) xml_value
{
itinerary_modified=xml_value;
}
-(void) dealloc
{
[itinerary_title release];
[itinerary_creator release];
[itinerary_identifiere release];
[itinerary_created release];
[itinerary_modified release];
[super dealloc];
}
#end
My question about.
1- Is this type Deceleration of NSString in this class of Memory Leak Issue. If Yes Please How i Will change this.
2- I am Using This class into Other class
Like that
itinerary_detail *check=[[itinerary_detail alloc] init];
[check itinerary_initialization];
[check release];
my question is this right way . or this is also a Memory Leak Issue.
Please Guide Me How to Deceleration Of this class and How to handle all memory Leak Issues.
Please Help Me
The problem come from the fact that you don't use the property but directly access the member variable. replace itinerary_title=xml_valueby self.itinerary_title=xml_value
btw, string properties are usually (copy) and not (retain) and why do you create all those methods while the synthesize will do it for you.
remove the methods from the .h file and from the .m file and set the property as
#property (copy) NSString* myString;
Your code shows that you need to get the basics of Cocoa and Objective-C right, before writing an actual program. Read Cocoa Fundamentals, OOP with Objective-C, etc. Resist the urge to start writing programs right now; the time you'll spend to learn the basics will greatly reduce your headache later.
Your code should look like:
#interface ItineraryDetail : NSObject {
NSString *itineraryTitle;
...
}
#property (retain) NSString *itineraryTitle;
#end
and
#implementation ItineraryDetail
#synthesize itineraryTitle, ... ;
-(id)init{
self=[super init];
if(self){
itineraryTitle=nil;
}
return self;
}
-(void) dealloc
{
[itineraryTitle release];
[super dealloc];
}
#end
and
ItineraryDetail *check=[[ItineraryDetail alloc] init];
... use it ...
[check release];
A few points:
In Objective-C, you don't usually name_like_this. You NameLikeThis. This is not an absolute rule, but it's customary, and you should follow it in general.
You don't write a method like ...Initialize separately. Rather, it's implemented using init, with [super init] inside it.
When you synthesize a property named foo via #synthesize foo, the setter setFoo: and the getter foo: are automatically generated, so you don't have to provide them manually. And you mistakenly used the name foo: for the setter! That will totally confuse the system.
The nil value for NSString (or any object in Objective-C in general) is not #"null" but just nil. And the ivars are set to nil automatically by the system, so you don't really do that in the initialization method.