我正在使用NSUSerDefaults为我的应用程序存储几个字符串和整数。每当打开视图时,字符串的加载速度都比视图慢,因此您会看到故障。例如,我保存了selectedSegmentIndex,然后在viewDidAppear中读取它,并在调用该视图的一小段时间内,未选择任何段,然后选择了正确的段。如何使打开的视图与读取的设置之间没有时间间隔?

- (void)viewDidLoad
{
    [super viewDidLoad];

    int segmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"selectedIndex"];
    unitSegmentControl.selectedSegmentIndex = segmentIndex;

    BOOL location = [[NSUserDefaults standardUserDefaults] boolForKey:@"locationManager"];
    [gpsSwitch setOn:location animated:NO];

    deviceID.text =  [[NSUserDefaults standardUserDefaults] stringForKey:@"DeviceID"];

}


- (IBAction)changeSeg:(id)sender {

    if (unitSegmentControl.selectedSegmentIndex == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:@"http://98.246.50.81/firecom/xml/units/E01.xml" forKey:@"parserURL"];
        [[NSUserDefaults standardUserDefaults] setObject:@"Hillsboro Main" forKey:@"selectedStation"];
        [[NSUserDefaults standardUserDefaults] setObject:@"Hillsboro Fire & Rescue" forKey:@"selectedDepartment"];
    }
    if (unitSegmentControl.selectedSegmentIndex == 1) {
        [[NSUserDefaults standardUserDefaults] setObject:@"http://98.246.50.81/firecom/xml/units/E02.xml" forKey:@"parserURL"];
        [[NSUserDefaults standardUserDefaults] setObject:@"Hillsboro Witch Hazel" forKey:@"selectedStation"];
        [[NSUserDefaults standardUserDefaults] setObject:@"Hillsboro Fire & Rescue" forKey:@"selectedDepartment"];
    }
    [[NSUserDefaults standardUserDefaults] setInteger:unitSegmentControl.selectedSegmentIndex forKey:@"selectedIndex"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

最佳答案

默认设置并不慢,您只是加载数据为时已晚。填充视图的标准位置是视图控制器中的-viewDidLoad-viewWillAppear。两者都将尽快更新视图以避免视觉故障。如果这两种方法都不适合您,请按以下提示查找原因:

  • 尝试将选定的索引设置为硬接线号码。这将告诉您问题出在默认值还是-setSelectedSegmentIndex调用中。
  • 将UI填充代码移动到-viewWillAppear。这是在更新UI之前的最新时刻。
  • 使用NSParameterAssert来确保unitSegmentControl不是nil
  • 确保从默认值读回的索引是期望的数字。通常,最好将默认键提取为常量。这样一来,您就不会碰到简单的错字错误:
    static NSString *const SelectedSegmentKey = @"selectedSegment";
    
  • 如果其他所有操作失败,请为您的UISegmentControl使用自定义unitSegmentControl子类,然后在-setSelectedSegmentIndex中放置一个断点,以查看还有谁在调用它。
  • 关于ios - iOS NSUserDefaults加载缓慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13996159/

    10-11 22:53
    查看更多