How do I access a custom object in memory from a view controller?

不羁的心 提交于 2019-12-11 06:28:43

问题


In my app I fetch a coredatabase and put results into an array called self.stores. I convert those store locations to MyLocation objects which have a distance property. I plot the MyLocation objects like so:

- (void)plotStorePositions:(NSString *)responseString {

    for (id<MKAnnotation> annotation in _mapView.annotations) {
        [_mapView removeAnnotation:annotation];
    }
    //CYCLE THRU STORE OBJECTS
    for (Store * storeObject in self.stores) {

        NSString * latitude = storeObject.latitude;
        NSString * longitude = storeObject.longitude;
        NSString * storeDescription = storeObject.name;
        NSString * address = storeObject.address;

        //CREATE MYLOCATION OBJECTS
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = latitude.doubleValue;
        coordinate.longitude = longitude.doubleValue;
        MyLocation *annotation = [[MyLocation alloc] initWithName:storeDescription address:address coordinate:coordinate distance:0];

        //CREATE A PIN FOR EACH MYLOCATION ANNOTATION
        CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];

        //SET USERLOCATION (Must move this code out)
        self.userLocation = [[CLLocation alloc] initWithLatitude:self._mapView.userLocation.coordinate.latitude longitude:self._mapView.userLocation.coordinate.longitude];

        //SET USERLOCATION TO APPDELEGATE (Must move this code out)
        AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        myDelegate.userLocation = self.userLocation;

        //CALCULATE DISTANCE AND SET ITS THAT MYLOCATION's DISTANCE PROPERTY
        CLLocationDistance calculatedDistance = [pinLocation distanceFromLocation:userLocation];
        annotation.distance = calculatedDistance/1000;        

        [_mapView addAnnotation:annotation];

    }

}

This is in a mapview. I then have a tableview where I fetch the same coredatabase and get self.stores again. Then I cycle through that array of self.stores to create STORE storeObjects to put into my tableview cells. But I want to sort those cells. How do I get MyLocation objects which should be in memory? Do I need to pass them to the appDelegate or to the tableview controller?


回答1:


As you are using Core Data, your best option is to use a NSFetchedResultsController to populate your table view.

All you need then is the managed object context, either from another controller or the app delegate.



来源:https://stackoverflow.com/questions/14879486/how-do-i-access-a-custom-object-in-memory-from-a-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!