2012-01-12 81 views
0

我有一个很奇怪的情况。我创建一个名为类的singletone对象“简介是这样的:单身物体的奇怪行为

static Profile *currentProfile; 

+ (Profile *)currentProfile 
{ 
@synchronized(self) 
{ 
    if (currentProfile == nil) 
     currentProfile = [[Profile alloc] init]; 
} 

return currentProfile; 
} 

- (id)init 
{ 
self = [super init]; 
if (self) 
{ 
    // Initialization code here. 
    isChecked = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isChecked"] boolValue];  

    if (isChecked) 
    { 
     NSLog(@"isChecked block is called"); 
     NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"myEncodedObjectKey"]; 
     self   = (Profile *) [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
     [self retain]; 

     for (int i = 0; i < self.avatar.count; i++) 
      [self.avatar replaceObjectAtIndex:i withObject:[UIImage imageWithData:[self.avatar objectAtIndex:i]]]; 
    } 

    else 
    { 
     password = @""; 
     pfefferID = @""; 
     email  = @""; 
     avatar = [[NSMutableArray alloc] initWithObjects: 
        [UIImage imageNamed:@"empty_image.png"], 
        [UIImage imageNamed:@"empty_image.png"], 
        [UIImage imageNamed:@"empty_image.png"], 
        [UIImage imageNamed:@"empty_image.png"], 
        [UIImage imageNamed:@"empty_image.png"],nil]; 
     isBoy  = YES; 
     friends = [[NSMutableDictionary alloc] init]; 
     rating = 0; 
    } 
    } 

return self; 
} 

在init()方法我检查通过使用名为布尔变量存储在NSUserDefaults的一定条件下‘器isChecked’器isChecked等于YES,一切工作正常。但是...我创建的AppDelegate此档案文件对象这样

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
users       = [[NSMutableDictionary alloc] init]; 
usersForLeaderboardFromServer = [[NSMutableDictionary alloc] init]; 
listOfFriendsFromServer  = [[NSMutableDictionary alloc] init]; 
currentProfile    = [Profile currentProfile]; 
sessionID      = 0; 

if (!currentProfile.isChecked)//why???? 
    NSLog(@"not checked"); 

if (currentProfile.isChecked) 
{ 
    [self getUsersForLeaderboardFromServer]; 

    MainMenuView *mainMenu = [[[MainMenuView alloc] init] autorelease]; 
    [self.navigationController pushViewController:mainMenu animated:YES]; 
} 
} 

所以同一变量器isChecked这一刻(远远低于实际的时刻)前等于YES变得等于NO使用时在应用程序didFinishLaunchingWithOptions方法通过点访问它。发生了什么?我能够处理它,但我只是很好奇阿博这种情况。你知道它有什么问题吗?

回答

2

你在init中重新分配self,所以你要返回新的对象而不是你设置isChecked的那个。看到这个代码:

self   = (Profile *) [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
[self retain]; 

这是略显尴尬到不喜欢的东西,你已经得到了 - 我肯定不会建议你有办法取代它。首先,当您重新指定self时,您设置为静态currentProfile的值不会更新,因此仍然是旧的。当你重新分配时,你也不会释放旧的self

要解决它,你可以做这样的事情:

id newSelf   = (Profile *) [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
newSelf.isChecked = isChecked; 
[self release]; 
self = [newSelf retain]; 

但我真的不主张个人。我建议你从档案中加载对象,然后用它更新自己,而不是重新指定自己。

+0

哦,我很傻,很明显...谢谢.. – 2012-01-12 15:12:34