2016-12-10 30 views
0

我試圖使用核心數據模型類作爲我的自定義註釋,但不知何故viewForAnnotation永遠不會被調用。無法在MapKit中使用核心數據模型類添加註釋

這是我的看法控制器,它包含所有的核心數據片斷以及如何實施委託方法

#import "SkyCastViewController.h" 
#import "AppDelegate.h" 
#import "Pixel-Swift.h" 
#import "Photo+Annotation.h" 


static NSString* const NavigationBarTitleFontName = @"Avenir-Heavy"; 
static CGFloat const NavigationBarTitleFontSize = 17; 
static NSString* const MapViewReuseIdentifier = @"AnnotationViweIden"; 

@interface SkyCastViewController() <MKMapViewDelegate> 

@property (weak, nonatomic) IBOutlet MKMapView *mapView; 
@property (strong, nonatomic) NSArray* photos; 
@property (strong, nonatomic) UIManagedDocument* document; 



@end 

@implementation SkyCastViewController 

- (void) viewDidLoad{ 
    [super viewDidLoad]; 
    [self updateUI]; 
    self.mapView.delegate = self; 
} 

- (void) viewDidAppear:(BOOL)animated{ 
    [super viewDidAppear:animated]; 
    NSFileManager* fileManager = [NSFileManager defaultManager]; 
    NSURL* docsDir = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; 
    if(docsDir){ 
     NSURL* url = [docsDir URLByAppendingPathComponent:@"storage"]; 
     self.document = [[UIManagedDocument alloc] initWithFileURL: url]; 
     if(self.document.documentState != UIDocumentStateNormal){ 
      if([[NSFileManager defaultManager] fileExistsAtPath: url.path]){ 
       //the document exists, open it 
       [self.document openWithCompletionHandler:^(BOOL success){ 
        if(success){ 
         [self documentInit]; 
        } 
       }]; 
      }else{ 
       //the document does not exist, create one 
       [self.document saveToURL:url forSaveOperation: UIDocumentSaveForCreating completionHandler:^(BOOL success){ 
        //post a notification that document is ready 
        if(success){ 
         NSLog(@"saveToURL succeed"); 
        }else{ 
         NSLog(@"saveToURL falied"); 
        } 
       }]; 
      } 
     } 
    } 

} 




// document ready observer 
- (void) documentInit{ 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSManagedObjectContext* context = self.document.managedObjectContext; 
     NSError* error; 
     //fetch objects 
     NSFetchRequest* request = [[NSFetchRequest alloc] initWithEntityName:@"User"]; 
     request.fetchBatchSize = 10; 
     request.fetchLimit = 100; 
     NSString* nameAttr = @"name"; 
     NSString* nameValue = @"Kesong Xie"; 
     request.predicate = [NSPredicate predicateWithFormat:@"%K like %@", nameAttr, nameValue]; 
     NSArray* users = [context executeFetchRequest:request error: &error]; 
     if(error != nil){ 
      NSLog(@"%@", error.localizedDescription); 
     }else{ 
      if([users count] > 0){ 
       for(User* user in users){ 
        self.photos = (NSArray<Photo<MKAnnotation>*>*)user.photo.allObjects; 
        [self.mapView addAnnotations:self.photos]; 
       } 
      } 
     } 
     NSLog(@"%@", self.photos); 
     //  [self.mapView showAnnotations: self.photos animated: YES]; 
    }); 

} 


//MARK: - UPATE UI 
- (void) updateUI{ 
    [self.navigationController.navigationBar setBarTintColor: [UIColor blackColor]]; 
    UIFont* titleFont = [UIFont fontWithName: NavigationBarTitleFontName size: NavigationBarTitleFontSize]; 
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: titleFont, NSForegroundColorAttributeName: [UIColor whiteColor]}]; 
} 

- (UIStatusBarStyle) preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
} 


//MARK: - MKMapViewDelegate 
-(MKAnnotationView*) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{ 
    NSLog(@"called from viewForAnnotation"); 
    if([annotation isKindOfClass:[ MKUserLocation class]]){ 
     return nil; 
    } 
    MKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier: MapViewReuseIdentifier]; 
    if(!annotationView){ 
     annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:MapViewReuseIdentifier]; 
    }else{ 
     annotationView.annotation = annotation; 
    } 
    UIImage* shot = [[UIImage alloc] initWithContentsOfFile:@"shot3"]; 
    annotationView.image = shot; 
    annotationView.frame = CGRectMake(0, 0, 60, 60); 
    annotationView.clipsToBounds = YES; 
    return annotationView; 
} 

@end 

現在在控制檯上的唯一輸出

Pixel[1832:440548] (
    "<Pixel.Photo: 0xa03a400> (entity: Photo; id: 0x17e905f0 <x-coredata://FB9198FE-57D1-4C88-945B-0B04D49821C0/Photo/p42> ; data: {\n latitude = \"32.88831721994364\";\n longitude = \"-117.2413945199151\";\n thumbnailData = nil;\n time = nil;\n title = \"Beach Walking\";\n whoTook = \"0xa040660 <x-coredata://FB9198FE-57D1-4C88-945B-0B04D49821C0/User/p10>\";\n})", 
    "<Pixel.Photo: 0xa039440> (entity: Photo; id: 0xa038b40 <x-coredata://FB9198FE-57D1-4C88-945B-0B04D49821C0/Photo/p43> ; data: {\n latitude = \"32.88831721994364\";\n longitude = \"-117.2413945199151\";\n thumbnailData = nil;\n time = nil;\n title = \"Aerial Shots of Sedona Arizona\";\n whoTook = \"0xa040660 <x-coredata://FB9198FE-57D1-4C88-945B-0B04D49821C0/User/p10>\";\n})" 
) 

回答

0

能否請您分享您的viewController代碼,因爲根據您的共享代碼,我可以假設您的MapView在此代碼之後啓動。您MapView類加載

2016-12-09 16:19:42.101997 Pixel[1646:397556] viewForAnnotation called 
2016-12-09 16:19:42.102120 Pixel[1646:397556] annotation is the MKUserLocation 

因爲在您的控制檯,這些線後打印

if(error != nil){ 
      NSLog(@"%@", error.localizedDescription); 
     }else{ 
      if([users count] > 0){ 
       for(User* user in users){ 
        self.photos = (NSArray<Photo<MKAnnotation>*>*)user.photo.allObjects; 
        [self.mapView addAnnotations:self.photos]; 
       } 
      } 
     } 
     NSLog(@"%@", self.photos); 

右這些行應你的CoreData之前打印結果

+0

如果它在覈心數據之前打印,但是我沒有在該點設置所有註釋?地圖視圖如何知道如何呈現與我的核心數據條目相關聯的註釋? –

+0

我已經附加了我的視圖控制器,並且還移動了此控制器中的所有核心數據,以便您可以更清楚地看到它。現在更新後的代碼只是使用符合MKAnnotation的核心數據'Photo:NSManagedObject'來設置一些引腳。 –

0

我想我明白我爲什麼不能現在加載我的PIN。該生產線

self.photos = (NSArray<Photo<MKAnnotation>*>*)user.photo.allObjects; 

嘗試分配所有photo(MKAnnotation)photos財產,但由於核心數據的斷層,直到你訪問它實際的「數據」不可用。

解決方案: 創建一個新MKAnnotation類稱爲PhotoAnnotation 下面是這個類的代碼 PhotoAnnotation.h

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 

@interface PhotoAnnotation : NSObject 

@property (nonatomic) CLLocationCoordinate2D coordinate; 

@property (strong, nonatomic) NSString* thumbnailUrl; 

- (id) initWithThumbnailUrl:(CLLocationCoordinate2D)coordinate url: (NSString*) thumbnailUrl; 

@end 

## PhotoAnnotation.m

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
#import "PhotoAnnotation.h" 

@interface PhotoAnnotation() <MKAnnotation> 

@end 

@implementation PhotoAnnotation 

- (id) initWithThumbnailUrl:(CLLocationCoordinate2D)coordinate url: (NSString*) thumbnailUrl{ 
    self = [super init]; 
    if(self){ 
     self.coordinate = coordinate; 
     self.thumbnailUrl = thumbnailUrl; 
    } 
    return self; 
} 

@end 

分配MKAnnotation這樣的

for(User* user in users){ 
        self.photos = [[NSMutableArray alloc] init]; 
        for(Photo* photo in user.photo){ 
         CLLocationCoordinate2D location = CLLocationCoordinate2DMake(photo.latitude, photo.longitude); 
         PhotoAnnotation* myAnnotation = [[PhotoAnnotation alloc]initWithThumbnailUrl: location url: photo.thumbnailUrl]; 
         [self.photos insertObject:myAnnotation atIndex:0]; 
        } 
       } 

這將成功地在地圖上創建自定義MKAnnotation!