我试图做一个自定义的MKAnnotation类,以便它可以容纳其他信息,但我一直收到此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [AnnotationForId setCoordinate:]: unrecognized selector sent to instance 0x16f63340'
我尝试查找如何创建一个,并且遵循了我在网上找到的内容,并且对为什么继续收到此错误感到困惑。
这是我的自定义注释类。
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
@interface AnnotationForId : NSObject <MKAnnotation >{
NSString *title;
NSString *subtitle;
CLLocationCoordinate2D coordinate;
NSInteger shopId;
}
@property(nonatomic)NSInteger shopId;
@property (nonatomic, copy) NSString * title;
@property (nonatomic, copy) NSString * subtitle;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@end
我已经在.m类中综合了属性变量。
我尝试在主控制器中调用自定义类:
for(Shop *shops in feed.shops){
NSLog(@"reached");
AnnotationForId *shop = [[AnnotationForId alloc] init];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(shops.latitude, shops.longitude);
shop.coordinate = coords;
//[[CLLocationCoordinate2DMake(shops.latitude, shops.longtitude)]];
shop.title = shops.name;
shop.subtitle = @"Coffee Shop";
[map addAnnotation:shop];
}
为什么这种方法行不通的任何帮助都会很棒。
谢谢。
最佳答案
似乎您正在尝试设置readonly属性。
您将其声明为只读:
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
但是,然后您尝试使用setter:
shop.coordinate = coords;
只读意味着不会为其他类定义要使用的设置器。
编辑:
我认为您应该在
AnnotationForId
类中添加便捷初始化程序,例如:-(id)initWithCoordinate:(CLLocationCoordinate2D)coord
{
self = [super init]; // assuming init is the designated initialiser of the super class
if (self)
{
coordinate = coord;
}
return self;
}
因此,您的代码将如下所示:
for(Shop *shops in feed.shops){
NSLog(@"reached");
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(shops.latitude, shops.longitude);
AnnotationForId *shop = [[AnnotationForId alloc] initWithCoordinate:coords];
//[[CLLocationCoordinate2DMake(shops.latitude, shops.longtitude)]];
shop.title = shops.name;
shop.subtitle = @"Coffee Shop";
[map addAnnotation:shop];
}
关于iphone - 在iOS中创建自定义注释类时遇到问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15682838/