iPhone check if user is logged in throughout application
For learning iOS programming I'm developing an iPhone application for sharing images. The application is the client fo开发者_StackOverflow中文版r a website.
In the method didFinishLaunchingWithOptions
I check if the user is already logged in.
If the user isn't logged in he can still see all parts of the applications but for example he wouldn't see option button for editing profile, comment on images, etc.
How can I share the logged/or not status throughout all view controllers?
Update: If giving this advice today, I would say use a shared instance:
@interface SomeClass: NSObject
{
+(SomeClass *)shared;
}
@implementation SomeClass
{
+(SomeClass *)shared {
static SomeClass *shared;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [SomeClass new];
});
return shared;
}
}
Then it is auto-instantiated for you on first use, and available throughout your app:
[[SomeClass shared] doSomething];
You can use a singleton - a global, shared instance of an object.
@interface SomeClassSingleton : NSObject {
}
+(SomeClass*)sharedSomeClass;
+(void)setSharedSomeClass:(SomeClass*)someObject;
@end
@implementation SomeClassSingleton
static SomeClass* _someObject = nil;
+(SomeClass*)sharedSomeClass
{
return _someObject;
}
+(void)setSharedSomeClass:(SomeClass*)someObject
{
@syncrhonized(self)
{
_someObject = someObject;
}
}
@end
Then, when you need to access your object in another source file, you import the header file for your singleton in the other header, like you would for any other reference.
Create a singleton:
SomeClass* someObject = [[SomeClass alloc] init];
[SomeClassSingleton setSharedSomeClass:someObject]; // write to save your singleton
Use/read a singleton:
[[SomeClass sharedSomeClass] someSharedClassMessage];
// OR
SomeClass* someObject = [SomeClass sharedSomeClass];
Or, you can create a singleton implementation that auto-inits the first time you access it:
@implementation SomeClassSingleton
static SomeClass* _someObject = nil;
+(SomeClass*)sharedSomeClass
{
@synchronized(self) {
if (_someObject == nil) {
_someObject = [[SomeClass alloc] init];
}
}
return _someObject;
}
@end
Put it in a singleton like the application delegate or as a transient value in a model object (like user data) that everything can see.
If you add an assigned BOOL property to your application delegate, you can get to it like this:
myApplicationDelegate *myDelegate = (myApplicationDelegate*)[[UIApplication sharedApplication] delegate];
myDelegate.userLoggedIn = YES;
精彩评论