我的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);
}

}

最佳答案

我发现了问题。您需要从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

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

10-08 18:52