财产保留在ios中

时间:2012-10-24 15:01:58

标签: objective-c ios

好的简单问题但找不到答案..

我需要将我的viewcontroller传递给按下按钮时调用的类中的方法“saveinfo”,如何使viewcontroller对“saveinfo”方法可见,以便我可以在那里使用它?

好的,我会添加全班。 Basicaly我需要在按下按钮时获取文本字段信息。但我无法访问我的saveinfo方法中的textFields和TableControll变量。

@implementation Settings

- (id)init: (TableViewController*) TableControll {
  NSMutableArray *textFields = [[NSMutableArray alloc] initWithCapacity:5];
    UITextField *textField = nil;

    for (int i = 0; i < 3; i++) {
        textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f+(i*35), 120.0f, 30.0f)];
        textField.backgroundColor = [UIColor whiteColor];
        [textField setBorderStyle:(UITextBorderStyleRoundedRect)];
        [TableControll.view addSubview:textField];

        [textFields addObject:textField];
        [textField release]; textField = nil;
    }
    UITextField *textName = textFields[0];
    textName.placeholder = @"Vardas";

    UITextField *textNo = textFields[1];
    textNo.placeholder = @"Telefonas";
    textNo.keyboardType = UIKeyboardTypeNumberPad;
    UITextField *textPin = textFields[2];
    textPin.keyboardType = UIKeyboardTypeNumberPad;
    textPin.placeholder = @"Pin";

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(150, 20, 160, 30);
    [button setTitle:@"Advanced settings" forState:UIControlStateNormal];
    [TableControll.view addSubview:button];
    UIButton *save = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    save.frame = CGRectMake(150, 60, 160, 30);
    [save setTitle:@"Save settings" forState:UIControlStateNormal];
    [TableControll.view addSubview:save];
    [button addTarget:self action:@selector(goAdvanced)
     forControlEvents:UIControlEventTouchUpInside];
    [save addTarget:self action:@selector(saveInfo)
     forControlEvents:UIControlEventTouchUpInside];

    return self;
}

-(void)goAdvanced {
    AppDelegate *newControll = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [newControll ChangeController];
}

-(void)saveInfo {

    for(int i=0;i<5;i++) {
        UITextField *tempTxtField=[_textFields objectAtIndex:i];
        NSLog(@"do it %@",tempTxtField.text);
    }

}

@end

1 个答案:

答案 0 :(得分:1)

只需将NSMutableArray作为ivar添加到您的班级:

@implementation TableControll {
    NSMutableArray *_textFields;
}

- (id)init: (TableViewController*) tableControll {
    _textFields = [[NSMutableArray alloc] initWithCapacity:5];

    //init the textfields
    //and add it as subview
}

// skipping the rest of the implementation

-(void)saveInfo {
    for(int i=0;i<5;i++) {
        UITextField *tempTxtField=[_textFields objectAtIndex:i];
        NSLog(@"do it %@",tempTxtField.text);
    }                 
}  
@end

您应该检查是否可以重复使用UITextFields或者每次都必须初始化NSMutableArray。你似乎不使用ARC,但你不应该写[textField release]; textField = nil;之类的东西。您希望释放对象以减少计数器,但不要将其设置为nil(dealloc除外)。