MapKit crashes - unrecognized selector sent to instance - iphone

I'm trying to add pin/address annotations in my Google maps view. When I do this everyting works fine:
[self addPin: CLLocationCoordinate2DMake(lat, lng) title: #"test" subtitle: #"test"];
with:
- (void) addPin: (CLLocationCoordinate2D) position title: (NSString *) pinTitle subtitle: (NSString *) pinSubtitle{
AddressAnnotation *addAnnotation = [[AddressAnnotation alloc] initWithTitle:pinTitle andCoordinate:position andSubtitle:pinSubtitle];
[mapView addAnnotation:addAnnotation];
[addAnnotation autorelease];
}
and
#import "AddressAnnotation.h"
#implementation AddressAnnotation
#synthesize title, coordinate, subtitle;
- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d andSubtitle:(NSString *)sbtitle {
[super init];
title = ttl;
coordinate = c2d;
subtitle = sbtitle;
return self;
}
- (void)dealloc {
[title release];
[super dealloc];
}
#end
with:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface AddressAnnotation : NSObject <MKAnnotation> {
NSString *title;
CLLocationCoordinate2D coordinate;
NSString *subtitle;
}
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d andSubtitle:(NSString *)sbtitle;
#end
things go wrong when I do this:
NSString *detailTitle = [NSString stringWithFormat:#"%#", [key objectForKey:#"name"]];
NSString *detailSubtitle = [NSString stringWithFormat:#"%#", [key objectForKey:#"vicinity"]];
NSLog(#"%#", detailSubtitle);
[self addPin: CLLocationCoordinate2DMake(lat, lng) title: detailTitle subtitle: detailSubtitle];
The app chrases somethimes when the pins are supposed to go in my view and somethimes this error:
'NSInvalidArgumentException', reason: '-[NSCFNumber length]: unrecognized selector sent to instance 0x5851c80'

Try changing your init function from AddressAnnotation.m to
- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d andSubtitle:(NSString *)sbtitle {
self = [super init];
if (self) {
self.title = ttl;
self.coordinate = c2d;
self.subtitle = sbtitle;
}
return self;
}
You are using the instance variables directly to set the values in the class instance and not the properties so the actual values that you pass are not copied hence not retained.

NSCFNumber is one of the private implementations of NSNumber. NSNumber does not have a method called length, so it does not recognize the selector. So far so good.
It is hard to tell where this NSNumber is being used. ISTM that the problem is not in your code. I don't know enough of MapKit to give you a workaround.

Related

Importing NSMutable Array into Map Annotations

Hi all i have a mysql database that consists of 7 columns and i have a script that reads it and extracts the data as JSON which i have pulled into an NSMutableArray, I want to be able to use this array to setup annotations on my Map but i'm not sure what to do here, as you can see i have defined one annotation here which shows up no problem but i'm honestly not sure how to show the NSMutableArray items? The NSMutable array will have more information than needed for the Annotations, I only need, coordinate, title and subtitle so how can i go about doing this? Here is my code so far:
hazards.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Hazards : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property (nonatomic, strong) NSString * ID;
#property (nonatomic, strong) NSString * ROUTE;
#property (nonatomic, strong) NSString * ADDRESS;
#property (nonatomic, strong) NSString * LATITUDE;
#property (nonatomic, strong) NSString * LONGITUDE;
#property (nonatomic, strong) NSString * HAZARD;
#property (nonatomic, strong) NSString * RISK;
// Methods
- (id) initWithID: (NSString *) hazardsID andROUTE: (NSString *) hazardsROUTE andADDRESS: (NSString *) hazardsADDRESS andLATITUDE: (NSString *) hazardsLATITUDE andLONGITUDE: (NSString *) hazardsLONGITUDE andHAZARD: (NSString *) hazardsHAZARD andRISK: (NSString *) hazardsRISK;
#end
hazards.m
#import "Hazards.h"
#implementation Hazards
#synthesize coordinate, title, subtitle, ID, ROUTE, ADDRESS, LATITUDE, LONGITUDE, HAZARD, RISK;
- (id) initWithID: (NSString *) hazardsID andROUTE: (NSString *) hazardsROUTE andADDRESS: (NSString *) hazardsADDRESS andLATITUDE: (NSString *) hazardsLATITUDE andLONGITUDE: (NSString *) hazardsLONGITUDE andHAZARD: (NSString *) hazardsHAZARD andRISK: (NSString *) hazardsRISK {
self = [super init];
if (self)
{
ID = hazardsID;
ROUTE = hazardsROUTE;
ADDRESS = hazardsADDRESS;
LATITUDE = hazardsLATITUDE;
LONGITUDE = hazardsLONGITUDE;
HAZARD = hazardsHAZARD;
RISK = hazardsRISK;
}
return self;
}
#end
viewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "Hazards.h"
#interface ViewController : UIViewController
#property (nonatomic, strong) NSMutableArray *json;
#property (nonatomic, strong) NSMutableArray *hazardsArray;
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#pragma mark - Methods
-(void) retrieveData;
#end
viewController.m
#import "ViewController.h"
#import "Hazards.h"
#interface ViewController ()
#end
// Railway Street Ballymena Coordinates
#define BALLYMENA_LATITUDE 54.857719;
#define BALLYMENA_LONGITUDE -6.280654;
// Span
#define THE_SPAN 0.01f;
#define getDataURL #"localhost:8888/rmb/json.php"
#implementation ViewController
#synthesize json, hazardsArray, mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Create the region
MKCoordinateRegion myRegion;
// Center
CLLocationCoordinate2D center;
center.latitude = BALLYMENA_LATITUDE;
center.longitude = BALLYMENA_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
// Set our mapview
[mapView setRegion:myRegion animated: YES];
// Annotation
NSMutableArray *locations = [[NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Hazards *myAnn;
// Pin to show Royal Mail Ballymena delivery office
myAnn = [[Hazards alloc] init];
location.latitude = BALLYMENA_LATITUDE;
location.longitude = BALLYMENA_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Royal Mail Ballymena";
myAnn.subtitle = #"111, Railway Street";
[locations addObject:myAnn];
[self.mapView addAnnotations:locations];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Methods
-(void) retrieveData {
NSURL *url = [NSURL URLWithString:getDataURL];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// Setup our hazards array
hazardsArray = [[NSMutableArray alloc] init];
for (int i =0; i < json.count; i++) {
// Create hazard object
NSString *hazardsID = [[json objectAtIndex:i] objectForKey:#"ID"];
NSString *hazardsROUTE = [[json objectAtIndex:i] objectForKey:#"ROUTE"];
NSString *hazardsADDRESS = [[json objectAtIndex:i] objectForKey:#"ADDRESS"];
NSString *hazardsLATITUDE = [[json objectAtIndex:i] objectForKey:#"LATITUDE"];
NSString *hazardsLONGITUDE = [[json objectAtIndex:i] objectForKey:#"LONGITUDE"];
NSString *hazardsHAZARD = [[json objectAtIndex:i] objectForKey:#"HAZARD"];
NSString *hazardsRISK = [[json objectAtIndex:i] objectForKey:#"RISK"];
Hazards *myHazards = [[Hazards alloc] initWithID:hazardsID andROUTE:hazardsROUTE andADDRESS:hazardsADDRESS andLATITUDE:hazardsLATITUDE andLONGITUDE:hazardsLONGITUDE andHAZARD:hazardsHAZARD andRISK:hazardsRISK];
// Add our hazards object to our hazards array
[hazardsArray addObject:myHazards];
}
// [self.mapView addAnnotation:hazardsArray];
}
#end
Many Thanks in Advance
Assuming your retrieveData correctly builds Hazard objects and is called at the right time you could either add them one at a time with this line inside the loop
[self.mapView addAnnotation:myHazards];
or all at once after the loop is finished
[self.mapView addAnnotations:hazardsArray];

How to extend MKPointAnnotation and add a property to it

I'm trying to extend MKPointAnnotation and add a property to for an NSString called dealLink.
I thought I set it up correctly, but I'm getting this error at the moment:
Property 'dealLink' not found on object of type 'MKPointAnnotation *'
Here's my code in a view controller called MapOffersViewController.m:
#pragma mark - Populate Map
- (void)populateMap:(MKMapView*)map withDeals:(NSArray*) deals
{
NSLog(#"Deals " );
for (NSDictionary *currentDeal in deals) {
CLLocationCoordinate2D ctrpoint;
ctrpoint.latitude = [[[currentDeal objectForKey:#"coords"] objectForKey:#"lat"] doubleValue];
ctrpoint.longitude =[[[currentDeal objectForKey:#"coords"] objectForKey:#"lng"] doubleValue];
MKPointAnnotation *dealAnnotation = [[MKPointAnnotation alloc] init];
dealAnnotation.coordinate = ctrpoint;
dealAnnotation.title = [currentDeal objectForKey:#"vendor"];
**dealAnnotation.dealLink = [currentDeal objectForKey:#"link"];**
NSDictionary *currDict = #{
#"EUR": #"€",
#"GBP": #"₤",
#"USD": #"$",
#"BRL": #"R$"
};
NSString *currName = [currentDeal objectForKey:#"currency"];
NSString *currency = [currDict objectForKey:currName];
dealAnnotation.subtitle = [NSString stringWithFormat:#"%#%i",currency,[[currentDeal objectForKey:#"price"] integerValue ]];
NSLog(#"current deal id is %#",[currentDeal objectForKey:#"id"]);
[map setDelegate:self];
[map addAnnotation:dealAnnotation];
}
}
I'm importing this class called MapAnnotation.h:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MapAnnotation : MKPointAnnotation
{
NSString *title;
NSString *subtitle;
NSString *dealLink;
CLLocationCoordinate2D coordinate;
}
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property (nonatomic, retain) NSString *dealLink;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- (id)initWithTitle:(NSString *)ttl subTitle:(NSString *)subttl dealLink:(NSString *)dealLnk andCoordinate:(CLLocationCoordinate2D)c2d;
#end
and it's .m:
#import "MapAnnotation.h"
#implementation MapAnnotation
#synthesize title,subtitle,dealLink,coordinate;
- (id)initWithTitle:(NSString *)ttl subTitle:(NSString *)subttl dealLink:(NSString *)dealLnk andCoordinate:(CLLocationCoordinate2D)c2d {
title = ttl;
subtitle = subttl;
dealLink = dealLnk;
coordinate = c2d;
return self;
}
#end
thanks for any help
I used Craig's answer below and this additional code to get this working:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
NSLog(#"callout tapped from del method %#", dealUrl);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:dealUrl]];
}
- (void)mapView:(MKMapView *)mapView1 didSelectAnnotationView:(MKAnnotationView *)mapView2
{
MapAnnotation *annotation = mapView2.annotation;
NSString *temp = annotation.dealLink;
dealUrl = temp;
// NSLog(#"temp is %#", temp);
}
You're creating an MKPointAnnotation and trying to access dealLink, which is only on MapAnnotations. You need to create a MapAnnotation
....
ctrpoint.longitude =[[[currentDeal objectForKey:#"coords"] objectForKey:#"lng"] doubleValue];
MapAnnotation *dealAnnotation = [[MapAnnotation alloc] init];
dealAnnotation.coordinate = ctrpoint;
....

Add subtitle to annotation using UICRouteAnnotation

UICRouteAnnotation *startAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate [[routePoints objectAtIndex:0] coordinate]
title:#"Origin"
subtitle:#"Subtitle Here"
annotationType:UICRouteAnnotationTypeStart];
I am trying to add a subtitle to this annotation but don't have much experience with UICRouteAnnotation and was not able to find much documentation on it. Adding "subtitle:" through exceptions.
What am I missing? Why doesn't the subtitle work when doing it like this?
What I didn't realize is that UICRouteAnnotation needed to be modified to accept a subtitle. Here is my updated h and m files for UICRouteAnnotation. Making the below changes fixed my issue so the code I posted in my question works as intended.
Thanks Anna for pointing me in the right direction.
.h file
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
typedef enum UICRouteAnnotationType {
UICRouteAnnotationTypeStart,
UICRouteAnnotationTypeEnd,
UICRouteAnnotationTypeWayPoint,
} UICRouteAnnotationType;
#interface UICRouteAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
UICRouteAnnotationType annotationType;
}
#property (nonatomic) CLLocationCoordinate2D coordinate;
#property (nonatomic, readonly, copy) NSString *title;
#property (nonatomic, readonly, copy) NSString *subtitle;
#property (nonatomic) UICRouteAnnotationType annotationType;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coord
title:(NSString *)aTitle
subtitle:(NSString *)aSubTitle
annotationType:(UICRouteAnnotationType)type;
#end
.m file
#import "UICRouteAnnotation.h"
#implementation UICRouteAnnotation
#synthesize coordinate;
#synthesize title;
#synthesize subtitle;
#synthesize annotationType;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coord
title:(NSString *)aTitle
subtitle:(NSString *)aSubTitle
annotationType:(UICRouteAnnotationType)type {
self = [super init];
if (self != nil) {
coordinate = coord;
title = [aTitle retain];
subtitle = [aSubTitle retain];
annotationType = type;
}
return self;
}
- (void)dealloc {
[title release];
[subtitle release];
[super dealloc];
}
#end

Set annotation's title as current address

I want to get the current location's address and set it to the annotation's title. But it didn't work. I think it's because of the block, but I don't know how to fix it. Any help will be appreciated. The most related code is as following:
WhereAmIAnnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface WhereAmIAnnotation : NSObject <MKAnnotation>
{
CLLocation *myLocation;
NSString *addr;
}
#property (nonatomic, retain) CLLocation *myLocation;
#property (nonatomic, copy) NSString *addr;
#end
WhereAmIAnnotation.m
#import "WhereAmIAnnotation.h"
#implementation WhereAmIAnnotation
#synthesize myLocation, addr;
- (CLLocationCoordinate2D)coordinate;
{
return self.myLocation.coordinate;
}
- (NSString *)title
{
return self.addr;
}
#end
MapViewController.m
- (IBAction)gotoCurrentLocation{
self.mapView.showsUserLocation = YES;//a bar button linked with this action
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocation *currentLocation = userLocation.location;
MKCoordinateRegion newRegion;
newRegion.center = currentLocation.coordinate;
newRegion.span.latitudeDelta = 0.02;
newRegion.span.longitudeDelta = 0.02;
[self.mapView setRegion:newRegion animated:YES];
WhereAmIAnnotation *whereAmIAnnotation = [[WhereAmIAnnotation alloc] init];
whereAmIAnnotation.myLocation = currentLocation;
whereAmIAnnotation.addr = [self addrAtLocation:currentLocation];
[self.mapView addAnnotation:whereAmIAnnotation];
self.mapView.showsUserLocation = NO;
}
- (NSString *)addrAtLocation:(CLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
self.addr = [NSString stringWithFormat:#"%# %# %# %#", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
return self.addr;
}
I should implement this method
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id )annotation{}
sorry for this stupid question!
You are returning the address while modifying it inside an asynchronous block. You should move the return inside the block, or a create a protocol to handle passing this information back to the caller.
Change the block to this:
- (void)addrAtLocation:(CLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
whereAmIAnnotation.addr = [NSString stringWithFormat:#"%# %# %# %#", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
}
Then make whereAmIAnnotation a member variable. Do you understand WHY this fixes your issues?
Create .h file
#interface MapPinClass : NSObject <MKAnnotation>{
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle,*color,*index,*locationId;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle,*color,*index,*locationId;
Create .m file
#implementation MapPinClass
#synthesize coordinate,title,subtitle,color,index,locationId;
-(void)dealloc{
[title release];
[super dealloc];
}
write a code where you set
MapPinClass *ann = [[MapPinClass alloc] init];
ann.title = AppMain.Heading;
ann.subtitle = AppMain.Detail;
ann.coordinate = region.center;
[myMapView addAnnotation:ann];
I should implement this method
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation{}
Sorry for that stupid question.

Unrecognized selector error with NSManagedObject getters/setters

I receive the following error. I can't figure out why, since latitude and longitude have #dynamic in the implementation file, and they are not reserved words (as far as I can tell). I am using RestKit with Core Data.
2011-11-06 18:12:23.428 Dark Sky Finder[19407:11903] Creating observation site #1
2011-11-06 18:12:23.431 Dark Sky Finder[19407:11903] -[ObservationSite setLatitude:]: unrecognized selector sent to instance 0x735fdf0
2011-11-06 18:12:23.431 Dark Sky Finder[19407:11903] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ObservationSite setLatitude:]: unrecognized selector sent to instance 0x735fdf0'
Code that causes the error:
if ([ObservationSite count:nil] == 0)
{
for (int i = 1; i <= 5; i++)
{
NSLog(#"Creating observation site #%i", i);
ObservationSite *site = [ObservationSite object];
site.observationSiteID = [NSNumber numberWithInt:i];
site.name = [NSString stringWithFormat:#"James's Place #%i", i, nil];
site.address = #"Somewhere";
site.latitude = [NSNumber numberWithDouble:30.3605+i];
site.longitude = [NSNumber numberWithDouble:-96.1852+i];
[[[RKObjectManager sharedManager] objectStore] save];
}
}
NSFetchRequest *fetchRequest = [ObservationSite fetchRequest];
NSArray *sites = [[ObservationSite objectsWithFetchRequest:fetchRequest] retain];
for (ObservationSite *site in sites)
{
NSLog(#"Name: %#", site.name);
NSLog(#"Address: %#", site.address);
NSLog(#"Latitude: %#", site.latitude);
NSLog(#"Longitude: %#", site.longitude);
}
ObservationSite header file:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <MapKit/MapKit.h>
#interface ObservationSite : NSManagedObject <MKAnnotation>
{
CLLocationCoordinate2D _coordinate;
NSString *_title;
NSString *_subtitle;
}
#property (nonatomic, retain) NSNumber *observationSiteID;
#property (nonatomic, retain) NSNumber *latitude;
#property (nonatomic, retain) NSNumber *longitude;
#property (nonatomic, retain) NSString *address;
#property (nonatomic, retain) NSString *name;
+ (ObservationSite *)mapAnnotation;
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate;
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title;
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title subtitle:(NSString *)subtitle;
#end
ObservationSite implementation file:
#import "ObservationSite.h"
#implementation ObservationSite
#synthesize coordinate = _coordinate;
#synthesize title = _title;
#synthesize subtitle = _subtitle;
#dynamic observationSiteID;
#dynamic latitude;
#dynamic longitude;
#dynamic address;
#dynamic name;
+ (ObservationSite *)mapAnnotation {
return [[[self alloc] init] autorelease];
}
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate {
return [self mapAnnotationWithCoordinate:coordinate title:nil subtitle:nil];
}
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title {
return [self mapAnnotationWithCoordinate:coordinate title:title subtitle:nil];
}
+ (ObservationSite *)mapAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title subtitle:(NSString *)subtitle {
ObservationSite *annotation = [[[self alloc] init] autorelease];
annotation.coordinate = coordinate;
annotation.title = title;
annotation.subtitle = subtitle;
return annotation;
}
#end
Whoops — the attribute names I used in the ObservationSite header/implementation files were different than in the data model. I renamed them now to be the same, and it works fine.