I’m fairly new to programming in Objective-C. While I have been able to find my way, there now is an issue I cannot solve, which is either caused by a mistake I made or because I have a fundamental misunderstanding about classes.
Essentially, I want one class to change a variable (or object) in another class. Here is the code I have:
// LocationManager.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface LocationManager : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
CLLocation *locationByCustomLocation;
}
@property (nonatomic, retain) CLLocation *locationByCustomLocation;
@end
Of course, there’s a corresponding implementation file: LocationManager.m. It synthesizes the locationByCustomLocation variable.
The point is that from another class, I’d like to manipulate the locationByCustomLocation variable.
// viewCustomLocation.h
#import <UIKit/UIKit.h>
@interface viewCustomLocation : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *tblLocation;
UITableViewCell *cell;
}
—
//viewCustomLocation.m
#import "viewCustomLocation.h"
#import "LocationManager.h"
@class LocationManager;
@implementation viewCustomLocation
@synthesize tblLocation;
@synthesize cell;
// some view related selectors here, but it boils down to this one:
- (void)dismissView:(id)sender
{
[self dismissModalViewControllerAnimated:YES];
LocationManager *locationManager = [[LocationManager alloc] init];
// I made sure with NSLog that the customLoc variable contains the expected data
CLLocation *customLoc = [[CLLocation alloc] initWithLatitude:place.coordinate.latitude longitude:place.coordinate.longitude];
[locationManager setLocationByCustomLocation:customLoc];
}
Now, if I use NSLog in LocationManager.m to see what’s in the LocationByCustomLocation variable, I would expect the same data as in customLoc. Instead, the variable still seems empty.
I think the problem is that I created a copy of the LocationManager class, thus filling the LocationByCustomLocation variable in the copied class, rather than the original one, which is what I want. I can’t figure out how to talk to the original LocationManager class.
I know of a few ways to work around this issue, but I would like to know how to achieve it this way to improve my fundamental understanding of the language.
Thanks for reading!
That’s because you are allocating a new instance of
LocationManager. You can either connect the two controllers between them, like declaring properties and setting them accordingly.For example, if you instantiate controller
Bfrom controllerA, you should implement a property for controllerB, likefirstController, so :and then from inside
Bcontroller, you control what happens in controllerAAn alternate way is to instantiate and control everything from the
ApplicationDelegate. It’s a more powerful pattern.