首先,您的代码有很多问题,但是除非这是性能关键的代码,否则您将每秒循环数百次(可能会创建许多自动释放的对象),使用alloc]init]方法只会使代码更难执行。(因为你必须在精神上经历并不断地平衡一个分配与一个释放)。别误会我,重要的是你要理解保留和释放等,但这是我解决问题的方法。
记住你在控制之中。使您的停车注释类能够“独立思考”一点。在下面的示例中,我添加了一个-(ID)initWithDictionary:这样您的另一个类就不必坐在那里一个接一个地设置键了。(有一些虚构的部分,我假设你会填补空白…
NSString * const PPAnnotationsKey = @"annotations";
NSString * const PPTitleKey = @"title";
NSString * const PPSubtitleKey = @"subtitle";
NSString * const PPLatitudeKey = @"latitude";
NSString * const PPLongitudeKey = @"longitude";
NSLog(@"loadAnnotations");
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"PermitData" ofType:@"plist"]; // autoreleased
NSDictionary *permitDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath]; // autoreleased
if ([[self title] isEqualToString:@"All Permits"]) {
for (NSString *parkingGroup in permitDictionary) {
NSLog(@"parkingGroup == %@", parkingGroup);
NSArray *annotations = [parkingGroup objectForKey:PPAnnotationsKey];
for (NSDictionary *entry in annotations) {
PPParkingAnnotation *annotation = [PPParkingAnnotation parkingAnnotationWithDictionary:entry]; // autoreleased
if (annotation) {
// assuming here that mapView's addAnnotation: will retain the
// annotation
[mapView addAnnotation:annotation];
}
}
}
}
@interface PPParkingAnnotation : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
+ (id)parkingAnnotationWithDictionary:(NSDictionary *)dictionary;
- (id)initWithDictionary:(NSDictionary *)dictionary;
@properties...
@end
@implementation PPParkingAnnotation
+ (id)parkingAnnotationWithDictionary:(NSDictionary *)dictionary {
return [[[[self class] alloc] initWithDictionary:dictionary] autorelease];
}
- (id)initWithDictionary:(NSDictionary *)dictionary {
[self setTitle:[dictionary objectForKey:PPTitleKey]];
[self setSubtitle:[dictionary objectForKey:PPTitleKey]];
// and so on.
}