ios - 修改 getter 以避免 NSNull

标签 ios objective-c

我有可能包含对象的 JSON 响应。在我的模型对象中,我这样做:

 _price3 = self.serverData[@"price3"];

我想做类似的东西:
 _price3 = self.serverData[@"price3"] ? self.serverData[@"price3"] : @"0";

问题是,在这样的构造中,它总是会评估为真,因为我猜是一个对象。

为了防止在我的属性中出现,我想将 getter 修改为变量,以检查值是 nsnull 的位置,如果是,则返回类似 @"0"的内容。那可能吗?

最佳答案

我在每个应用程序中都使用这种方法。

-(NSString*)checkNullValidation:(NSString *)key {
    NSString *returnValue;
    if(key == (id)[NSNull null] || [key isEqual:[NSNull null]] || key == nil) {
        returnValue = @"";
    }
    else {
        returnValue = [NSString stringWithFormat:@"%@",key];
    }
    return returnValue;
}

因此,每当我解析数据时,我都会进行如下检查
例如。,
NSDictionary *dictionaryTest = @{@"MyFirstKey":nil, @"MySecondKey":@"AwesomeValue"};
NSString *firstValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MyFirstKey"]]; // It will be @"" instead of nil
NSString *secondValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MySecondKey"]]; // It will be @"AwesomeValue"

因此,您获得 nil 的可能性为 0%。或 NULL并且应用程序不会崩溃。即使响应正文中不存在您的 key ,此操作也将起作用。

如果您想在多个屏幕上使用它,请创建一个通用处理程序类并将其添加为类方法并使用它。我几乎在所有应用程序中都使用过,并且我的应用程序从未因此而崩溃 nilNULL问题。

关于ios - 修改 getter 以避免 NSNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440004/

相关文章:

ios - map 套件位置图像

ios - Swift 3 - 如何声明 NSOrderedSet 以使用 setVocabularyStrings?

objective-c - 在现代 Objective-C 中覆盖 setter 和 getter 时访问生成的 ivar 时出错

iphone - 带有 UINavigationController 的 UITabBarController

iphone - 了解 Objective-C 中的协议(protocol)继承

ios - 将 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange 缓冲区转换为 RGB 缓冲区会创建蓝色图片

ios - 在 objective-c 中创建动态 TableView 的多个异步请求

c++ - Xcode 7 和 openCV(无 Swift): Core. hpp header 必须编译为 C++

ios - 动态访问变量

ios - 如何在 Objective-C 中更改标签栏的背景图像?