EcksMedia
EcksMedia

Reputation: 461

iOS Getter and Setter confusion

I think that I am a bit confused about iOS @property getter and setters. I am trying to set an NSString iVar in my AppDelegate.h file from another class so that it can be used by all of the classes in the project?

For example, I am working on an iPhone project that stores an iVar NSString *currentUser in AppDelegate.h. I need to be able to set this through one method in a ViewController.m and then get it through another method in a second ViewController?

Maybe Getter and Setter is the wrong direction of attack all together? I understand that i don't want to alloc init the AppDelegate as the iVar will only exist in that object and I want it accessible to ALL objects in ALL classes?

Please someone set me straight.

All the best, Darren

Upvotes: 0

Views: 2017

Answers (1)

Bill Garrison
Bill Garrison

Reputation: 2049

Here's the setup for the app delegate.

@interface AppDelegate
{
   NSString *__currentUser;
}
@property (monatomic, copy) NSString* currentUser;
@end

@implementation AppDelegate
@synthesize currentUser = __currentUser;

- (void) dealloc
{
   [__currentUser release];
   [super dealloc];
}
@end

From one view controller, you could set a value for the current user, and from a subsequent view controller, get that value for some nefarious purpose.

@implementation LoginController
- (void) viewDidLoad
{
    ...
    AppDelegate *bob = [[UIApplication sharedApplication] delegate];
    [bob setCurrentUser: @"Jim Kirk"];
    ...
}
@end

In some other view controller that appears later, the value of the current user can be accessed.

@implementation ProfileViewController
- (void) viewDidLoad
{
   ...
   AppDelegate *bob = (AppDelegate *)[[UIApplication sharedApplication] delegate];
   NSString * user = [bob currentUser];

   // insert nefarious purpose for current user value here
   ...
}
@end

Upvotes: 1

Related Questions