UISwitch ViewDidLoad设置为On

时间:2011-05-01 16:24:13

标签: iphone core-data viewdidload uiswitch

我有一个UISwitch,它在CoreData中将BOOL设置为1或0。但是,当用户使用Switch加载视图时,核心数据会识别Switch设置为1(打开),但交换机仍然显示为关闭。这是下面的代码。注意:当您进入和退出应用程序时,开关会正确显示,但如果您关闭一个手机,或者停止并启动iPhone模拟器,它将显示。有人可以帮忙吗?

" setSwtich"是UISwitch上的方法," list"是UISwitch和"指示符的名称"是BOOL存储在其中的核心数据事件属性。

-(IBAction)setSwitch
{
    if (list.on) 
    {
        [event setIndicator:[NSNumber numberWithInt:1]];
        NSError *error;
        if (![managedObjectContext save:&error]) 
        {
            NSLog(@"there was an error in Save");
        }
    }
    else [event setIndicator:[NSNumber numberWithInt:0]];
    NSError *error;
    if (![managedObjectContext save:&error]) 
    {
        NSLog(@"there was an error in Save");
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (event.indicator == [NSNumber numberWithInt:1]) {
        [list setOn:YES animated:NO];
    }
    else nil;
}

-(void)viewDidAppear:(BOOL)animated
{
    if (event.indicator == [NSNumber numberWithInt:1]) {
        [list setOn:YES animated:NO];
    }
}

- (void)viewDidUnload
{
    if (list.on) {
        [event setIndicator:[NSNumber numberWithInt:1]];
    }
    NSError *error;
    if (![managedObjectContext save:&error]) 
    {
        NSLog(@"there was an error in Save");
    }
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void)viewDidDisappear:(BOOL)animated
{
    if (list.on) {
        [event setIndicator:[NSNumber numberWithInt:1]];
    }
    NSError *error;
    if (![managedObjectContext save:&error]) 
    {
        NSLog(@"there was an error in Save");
    }
}

1 个答案:

答案 0 :(得分:2)

也许只是你使用==的方式。尝试Apple定义的比较:

isEqualToNumber:

Returns a Boolean value that indicates whether the receiver and a given number are equal.
- (BOOL)isEqualToNumber:(NSNumber *)aNumber
Parameters

aNumber

    The number with which to compare the receiver.

Return Value

YES if the receiver and aNumber are equal, otherwise NO.
Discussion

Two NSNumber objects are considered equal if they have the same id values or if they have equivalent values (as determined by the compare: method).

This method is more efficient than compare: if you know the two objects are numbers.