私は iOS プログラミングの初心者で、シングルトン クラスとは何か、なぜそれが使用されるのかに非常に興味があります。いくつかの情報を見つけましたが、あいまいです。特に、実際の例に適用したいと思います。私のプロジェクトは Facebook SDK を使用しており、友人リストを含む NSDictionary のシングルトン クラスを作成したいと考えています。私の .m 委任ファイル:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//here is some other code
facebook = [[Facebook alloc] initWithAppId:@"my app id" 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]) {
NSArray *permissions = [[NSArray alloc] initWithObjects:
@"user_location",
@"friends_location",
@"read_friendlists",
nil];
[facebook authorize:permissions];
[permissions release];
}
[facebook requestWithGraphPath:@"me/friends" andDelegate:(id)self];
//here is some other code
}
そして、フレンド リストを返すリクエストの NSDictionary 値を設定します。
- (void)request:(FBRequest *)request didLoad:(id)result {
_friendsDictionary = result;
}
その方法では、シングルトン クラスを記述する必要があり、デリゲート クラスを使用しませんAppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
。