如何在Objective-C中改进以下代码?

时间:2011-08-30 17:30:06

标签: ios4

我有以下代码根据结果显示警报:如何改进以下代码:

-(IBAction)saveSettings:(id)sender

{     UIAlertView * alert = nil;

username = self.usernameTextField.text; 
token = self.passwordTextField.text; 

// validate the username and token
if(![self isValid]) 
{
    // show alert that it is not valid

    alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Invalid User Name or Password" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];


    [alert show];
    return; 
}

BOOL isSynched = [self syncSettings];

if(!isSynched) 
{
    alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error Syncing Settings" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
    [alert show];
}
else 
{
    alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Settings has been Synced Syncing" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
    [alert show];

}    

}

我想我会多次实例化警报,看起来有点重复!

2 个答案:

答案 0 :(得分:3)

username = self.usernameTextField.text; 
token = self.passwordTextField.text; 

UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                message:@""
                                               delegate:self
                                      cancelButtonTitle:nil
                                      otherButtonTitles:@"Ok", nil];
[alert autorelease];

// validate the username and token
if(![self isValid]) 
{
    // show alert that it is not valid

    alert.message = @"Invalid User Name or Password";
    [alert show];
    return; 
}

BOOL isSynched = [self syncSettings];

if(!isSynched) 
{
    alert.message = @"Error Syncing Settings";
}
else 
{
    alert.title = @"";
    alert.message = @"Settings has been Synced Syncing";

}    
[alert show];

答案 1 :(得分:1)

尝试将[alert show];的所有实例保留为&然后在最后放......

if (!alert) return;
[alert show];

phix23的答案也提供了很好的改进,因为你明确地设置了警报的一堆属性&只有一次。如果您使用它,您也可以通过将条件更改为...来使用我的

if (alert.message != @"") return;

干杯,佩德罗:)