ios - 如何防止记录负数或零数
<p><p>我的 xCode 应用程序有问题。</p>
<p>我的申请是关于记录结果的。因此项目值应该是正数。我尝试在选择项目时防止记录负值或零值,但我的代码不起作用。 </p>
<p>这是我记录项目的代码</p>
<pre><code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView* alert = [ initWithTitle:@"Outcome Item Value" message:@"Please enter an outcome item value" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
}
else
{
OutcomeItem* newOutcomeItem = ;
newOutcomeItem.outcomeName = self.selectedOutcomeItem.outcomeName;
newOutcomeItem.outcomeValue = .text doubleValue]];
if (newOutcomeItem.outcomeValue <= 0) {
NSLog(@"Invalid Value");
;
}
else
{
;
;
}
}
}
</code></pre>
<p>我的 OutcomeItem.h 是 </p>
<pre><code>#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;
</code></pre>
<p>OutcomeItem.m 是</p>
<pre><code>#import "OutcomeItem.h"
#import "OutcomeRecord.h"
@implementation OutcomeItem
@dynamic outcomeName;
@dynamic outcomeValue;
@dynamic outcomeRecord;
@end
</code></pre>
<p>添加结果项的方法是</p>
<pre><code>-(void)addOutcomeItem:(OutcomeItem *)outcomeItem
</code></pre>
<p>{
;
self.outcomeRecordItemList = ;</p>
<pre><code>;
NSError* error;
if (!) {
NSLog(@"Could not save outcome item insertion:\n%@", error.userInfo);
}
</code></pre>
<p>}</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我发现了问题。您需要从 NSNumber 转换为 doubleValue。</p>
<pre><code> NSNumber *outcomeValueX = .text doubleValue]];
if (outcomeValueX.doubleValue <= 0) {
NSLog(@"Invalid Value");
}
</code></pre>
<p>理想情况下,我会尝试使用 UITextFieldDelegate 对您的 UITextField 进行验证,并实现 textField:shouldChangeCharactersInRange:replacementString。</p>
<p>请看这里:<a href="https://stackoverflow.com/questions/9344159/validate-numeric-input-to-uitextfield-as-the-user-enters-input" rel="noreferrer noopener nofollow">How to Test Character Input to UITextField as the User Enters Characters and Prevent Invalid Characters</a> </p>
<p>在验证值之前,我也不会添加新的结果项。 </p></p>
<p style="font-size: 20px;">关于ios - 如何防止记录负数或零数,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/24243052/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/24243052/
</a>
</p>
页:
[1]