I have a logic issue. I need to access an instance of an object from another class.
I have a class called FacebookController. It has several delegate methods in it, for example fbDidLogin. First the facebookloginButtonClicked method gets executed when the user clicks on a button, and after some internal processing, the fbDidLogin method will get called, and the user will log in to the application. (All of this works perfectly).
Now I need to log out from the application. There is a delegate method called logout, and I have to call it as [facebook logout].
I have added a method called -(void) logoutFacebook. When the user clicks the logout button, the following method is called. The logout method is as follows;
-(void) logoutFacebook {
[facebook logout];
}
Logout works only if I log out (call logoutFacebook method) from the same viewController.
For instance if I am in a class called Student, I am trying to call the logoutFacebook method of FacebookController. My approach is as follows;
FacebookController *facebookController = [[FacebookController alloc]]init;
[facebookController logoutFacebook];
This doesn’t work, because by doing this, it will create a new instance of FacebookController . So I need to somehow access the original facebook object which was in the FacebookController (which was created after login). How do I get access this object ?
The code:
-(void)facebookloginButtonClicked:(id)sender{
facebook = [[Facebook alloc] initWithAppId:@"3232232" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"]
&& [defaults objectForKey:@"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:nil];
}
}
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[ facebook accessToken] forKey:@"FBAccessTokenKey"];
[defaults setObject:[ facebook expirationDate] forKey:@"FBExpirationDateKey"];
[defaults synchronize];
}
-(void) logoutFacebook {
[facebook logout];
}
in
FacebookController.mclass add this code above the @implementationadd the following function to the .h file
Implementation of the above function in the .m file
Now wherever you want to use the Facebook object ..use it like this
Now you will only have one instance of
FacebookControllerclass in your app’s whole lifetime..This is called Singleton pattern..You can find google it to get more detail on it.References: