Object-c的单例设计

来源:互联网 发布:淘宝运营方案 编辑:程序博客网 时间:2024/06/06 20:20

贡献一个单例的例子 供大家学习!

- (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