Object-c的單例設計

貢獻一個單例的例子 供大家學習!

- (id)init
{
    if ( self = [super init] )  
    {

  info = [[NSMutableDictionary dictionaryWithContentsOfFile:getFullPath(@"localUserInfo")]retain];
  if (!info) {
   info = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
     @"",@"phoneNumber",
     @"",@"nickName",
     nil]retain];
  }
 }
 return self;
}

+ (LocalUserInfo *)sharedSingleton
{
 static LocalUserInfo *sharedSingleton;
 
 @synchronized(self)
 {
  if (!sharedSingleton)
   sharedSingleton = [[LocalUserInfo alloc] init];
  
  return sharedSingleton;
 }
}

+ (NSString *)phoneNumber{

 return [[[LocalUserInfo sharedSingleton] info] objectForKey:@"phoneNumber"];

}
+ (NSString *)nickName{
 
 return [[[LocalUserInfo sharedSingleton] info] objectForKey:@"nickName"];
 
}
+ (void)setPhoneNumber :(NSString *) data{
 [[[LocalUserInfo sharedSingleton] info] setObject:data forKey:@"phoneNumber"];
 [[[LocalUserInfo sharedSingleton] info] writeToFile:getFullPath(@"localUserInfo") atomically:NO];
}

+ (void)setNickName:(NSString *) data{
 
 [[[LocalUserInfo sharedSingleton] info] setObject:data forKey:@"nickName"];
 [[[LocalUserInfo sharedSingleton] info] writeToFile:getFullPath(@"localUserInfo") atomically:NO];
}
@end

發佈了65 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章