Objective C中检查数据库中的空string的正确方法是什么?

我想限制在数据库时在数据库中没有数据在行中比不能显示exception我只是想限制空值

if ([[Utility checkNullValues:tInfo.product_price]isEqualToString:@""]) { [Utility showAlertView:@"Sorry" message:@"No Product You Buy." viewcontroller:self]; } 

这是错误的:

2015-06-03 12:35:38.320 NiColi [28363:2438247] *由于未捕获的exception'NSInvalidArgumentException',原因:'* + [NSString stringWithUTF8String:]:NULL cString'*** 终止应用程序 ***第一次抛出调用堆栈:

 NSString *str = ((char *)sqlite3_column_text(compiledStatement, 1)) ? [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)] : nil; 

你可以使用这个macros:

 #define NULL_VALIDATION(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; }) 

如果传递的对象是NULL或者对象本身,这个macros将返回nil 。 用法:

 if ([NULL_VALIDATION(tInfo.product_price) length] == 0) { [Utility showAlertView:@"Sorry" message:@"No Product You Buy." viewcontroller:self]; } 

PS:不要忘记导入<objc/runtime.h>

尝试这个-

 + (id)validateNullFields:(id)value{ if (value != NULL && ![value isKindOfClass:[NSNull class]]) { return value; } return nil; } 

我希望这可以帮助你…

 -(BOOL)isNullString:(NSString *)dbString{ if ([dbString isKindOfClass:[NSNull class]]) { return YES; } else if (dbString == nil){ return YES; } else if ([dbString isEqualToString:@""]){ return YES; } else if ([dbString isEqualToString:@"null"]){ return YES; } else if ([dbString isEqualToString:@"(null)"]){ return YES; } else if ([dbString caseInsensitiveCompare:@"NULL"] == NSOrderedSame){ return YES; } else if (dbString == 0){ return YES; } else{ return NO; } return NO; } 

它对于空值返回YES ,对某些值返回NO

我会给你提供最好的,更好的解决scheme。即使你通过了这个,它也给你一个很好的答案。所以你可以简单地使用这个方法。

 #pragma mark - check string is empty or not - (void)checkEmpty:(NSString *)check { @try { if (check.length==0) check = @" "; if([check isEqual:[NSNull null]]) check = @" "; } @catch (NSException *exception) { check = @" "; } } 

只要调用这个方法(用string(参数)),你想发送数据到数据库。