如何防止记录负数或零数

时间:2014-06-16 11:50:36

标签: ios objective-c

我的xCode应用程序出了问题。

我的申请是关于记录结果。因此,项目值应为正数。我尝试在选择项目时防止记录负值或零值,但我的代码不起作用。

这是我记录项目的代码

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Outcome Item Value" message:@"Please enter an outcome item value" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;

[alert show];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if (buttonIndex == 0) {

  }
  else
  {
    OutcomeItem* newOutcomeItem = [NSEntityDescription insertNewObjectForEntityForName:@"OutcomeItem" inManagedObjectContext:self.managedObjectContext];


    newOutcomeItem.outcomeName = self.selectedOutcomeItem.outcomeName;
    newOutcomeItem.outcomeValue = [NSNumber numberWithDouble:[[alertView textFieldAtIndex:0].text doubleValue]];


    if (newOutcomeItem.outcomeValue <= 0) {

        NSLog(@"Invalid Value");
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {

        [self.delegate addOutcomeItem:newOutcomeItem];
        [self.navigationController popViewControllerAnimated:YES];
    }
  }
}

我的OutcomeItem.h是

#import<Foundation/Foundation.h>
#import<CoreData/CoreData.h>
@class OutcomeRecord;
@interface OutcomeItem : NSManagedObject
@property (nonatomic, retain) NSString *outcomeName;
@property (nonatomic, retain) NSNumber *outcomeValue;
@property (nonatomic, retain) OutcomeRecord *outcomeRecord;
@end;

OutcomeItem.m是

#import "OutcomeItem.h"
#import "OutcomeRecord.h"

@implementation OutcomeItem
@dynamic outcomeName;
@dynamic outcomeValue;
@dynamic outcomeRecord;
@end

添加结果项方法是

-(void)addOutcomeItem:(OutcomeItem *)outcomeItem

{     [self.currentOutcomeRecord addOutcomeItemsObject:outcomeItem];     self.outcomeRecordItemList = [self.currentOutcomeRecord.outcomeItems allObjects];

[self.tableView reloadData];
NSError* error;
if (![self.managedObjectContext save:&error]) {
    NSLog(@"Could not save outcome item insertion:\n%@", error.userInfo);
}

}

1 个答案:

答案 0 :(得分:1)

我发现了这个问题。你需要从NSNumber转换为doubleValue。

 NSNumber *outcomeValueX = [NSNumber numberWithDouble:[[alertView textFieldAtIndex:0].text doubleValue]];

 if (outcomeValueX.doubleValue <= 0) {  
        NSLog(@"Invalid Value");
 } 

理想情况下,我会尝试使用UITextFieldDelegate对您的UITextField进行验证,并实现textField:shouldChangeCharactersInRange:replacementString。

见这里:How to Test Character Input to UITextField as the User Enters Characters and Prevent Invalid Characters

在验证值之前,我也不会添加新的outcomeItem。