0

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

“setSwtich”是 UISwitch 上的方法,“list”是 UISwitch 的名称,“indicator”是存储 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");
    }
}
4

1 回答 1

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.
于 2011-05-01T16:43:38.330 回答