Trying To Add Custom Image To Annotation


#1

I was wondering if anyone can tell me why this code is not working to add a custom image to an annotation. Tried to figure this out from the documentation but I’m obviously missing something.

BNRMapPoint.h

[code]#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface BNRMapPoint : NSObject
{
}
// A new designated initializer for instances of BNRMapPoint

  • (id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t;

// This is a required property from MKAnnotation
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

// For custom image
@property (nonatomic, retain) UIImage *image;

// This is an optional property from MKAnnotation
@property (nonatomic, copy) NSString *title;

@end[/code]

BNRMapPoint.m

[code]#import “BNRMapPoint.h”

@implementation BNRMapPoint

@synthesize coordinate, title, image;

  • (id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t
    {
    self = [super init];
    if (self) {
    coordinate = c;
    [self setTitle:t];
    UIImage *i = [UIImage imageNamed:@“tom.png”];
    [self setImage:i];
    }
    return self;
    }

  • (id)init
    {
    return [self initWithCoordinate:CLLocationCoordinate2DMake(43.07, -89.32)
    title:@“Hometown”];
    }

@end[/code]

I’m new to coding so any help would be appreciated.


#2

Have you added the image file tom.png to your project?


#3

Yes, the image file “tom.png” is in the ‘Supporting Files’ folder and is listed under ‘Copy Bundle Resources’ under the ‘Build Phases’ tab. Is there something else that I need to do to link it to the project?


#4

Then check to see if [UIImage imageNamed:@“tom.png”] is returning a nil. If you see a nil, then that will be one reason.


#5

It is not returning nil. If I set a breakpoint right after the assignment. ‘i’ appears to be pointing to a valid memory location.


#6

Your setImage only saves the image in your class, but there is no image propery in MKAnnotation.
However I guess one could access the MKAnnotationView object to specify the image there.