将值分配给UILabel时,模拟器崩溃

时间:2011-01-03 18:33:01

标签: iphone ios cocoa-touch

我有这个代码,出于某种原因,每当我尝试更改标签的文本时都会崩溃。

- (void) viewDidLoad {
    [super viewDidLoad];
    NSString * path = [[NSBundle mainBundle] pathForResource:@"Subs" ofType:@"plist"];
    NSMutableDictionary * modelDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    NSDictionary * yearDict = [modelDict valueForKey:Sub_Model];
    for (NSString * yearKey in yearDict) {
        NSDictionary * sizeDict = [yearDict valueForKey:yearKey];
        mount_depth = round([[[sizeDict valueForKey:Sub_Size] objectForKey:@"Mounting Depth"] floatValue]);
        displacement = round([[[sizeDict valueForKey:Sub_Size] objectForKey:@"Displacement"] floatValue]);
        sealed_min = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Sealed Min."] floatValue];
        sealed_max = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Sealed Max."] floatValue];
        ported_min = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Ported Min."] floatValue];
        ported_max = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Ported Max."] floatValue];
        minportlen = [[sizeDict valueForKey:Sub_Size] objectForKey:@"Min. Port Len."];
        maxportlen = [[sizeDict valueForKey:Sub_Size] objectForKey:@"Max. Port Len."];
    }
    // [self loadEnclosure];
    portlenLbl.hidden = FALSE;
}

然后我对导航项目进行了分段控制,以根据用户选择的内容更改标签,并且只要他们选择非默认值就是程序崩溃时。

- (IBAction) boxSize:(id)sender {
    // [self loadEnclosure];
    switch (self.boxControl.selectedSegmentIndex) {
        case 0:
            portlenLbl.text = (@"%@", minportlen);
            break;
        case 1:
            portlenLbl.text = (@"%@", maxportlen);
            break;
        default:
            break;
    }
}

我还应该补充说,在达到这一点之前有多个视图,并且使用类似于此的方法调用它们:

- (IBAction) GetBox:(id)sender {
    K_Box * KView = [[K_Box alloc] initWithNibName:nil bundle:nil];

    KView.Num_Subs = self.Num_Subs;
    KView.Box_Type = self.Box_Type;
    KView.Box_Shape = self.Box_Shape;
    KView.Sub_Model = self.Sub_Model;
    KView.Sub_Size = self.Sub_Size;
    [self presentModalViewController:KView animated:YES];
}

2 个答案:

答案 0 :(得分:2)

您的真正问题在于:

minportlen = [[sizeDict valueForKey:Sub_Size] objectForKey:@"Min. Port Len."];
maxportlen = [[sizeDict valueForKey:Sub_Size] objectForKey:@"Max. Port Len."];

objectForKey:返回一个自动释放的对象,您可以直接将其分配给实例变量。当您的应用程序到达boxSize:方法时,这些值超出了范围,因为它们是从管理它们的自动释放池中排出的。因此,解决方案只需retain objectForKey:的返回值,然后直接将其分配给您的实例变量:

minportlen = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Min. Port Len."] retain];           
maxportlen = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Max. Port Len."] retain];

(当然,如果您将实例变量定义为属性,则应使用指定的属性setter。)

答案 1 :(得分:0)

只需使用portlenLbl.text = [[NSString stringWithFormat:@“%@”,maxportlen]; 。 并且请记住,每当设置标签文本时,请使用上述语法。