if ([dictInfoForThisBusiness[@"LikeNumber"] isNotEmpty]) {
BusinessToSave.numberOfLike =dictInfoForThisBusiness[@"LikeNumber"];
}
else
{
BusinessToSave.numberOfLike = @(0);
}
if (dictInfoForThisBusiness[@"DislikeNumber"])
{
BusinessToSave.numberOfDislike =dictInfoForThisBusiness[@"DislikeNumber"];
}
else
{
BusinessToSave.numberOfDislike =@(0);
}
//BusinessToSave.buildingName =dictInfoForThisBusiness[@"Building"];
if([dictInfoForThisBusiness[@"Building"] isNotEmpty]){
BusinessToSave.buildingName=dictInfoForThisBusiness[@"Building"];
}
else
{
BusinessToSave.buildingName =nil;
}
if([dictInfoForThisBusiness[@"Street"] isNotEmpty]){
BusinessToSave.Street=dictInfoForThisBusiness[@"Street"];
}
else
{
BusinessToSave.Street =nil;
}
显然,由于一个简单的原因,这是非常混乱的。
BusinessToSave
是一个托管对象。
通常它应该只是零。但是,字典不能包含nil值,而是返回NULL。
所以我不能只做BusinessToSave.buildingName = dictInfoForThisBusiness[@"Building"]
那我该怎么办?
我尝试过的一件事是:
BusinessToSave.buildingName =(NSString*) [dictInfoForThisBusiness[@"Building"] nilIfNull];
我尝试的另一件事是
BusinessToSave.buildingName =((NSString*) dictInfoForThisBusiness[@"Building"]).nilIfNull;
我不知道为什么点符号可以工作,因为nilIfNull返回id
-(id) nilIfNull
{
if ([self isKindOfClass:[NSNull class]])
{
return self;
}
else
{
return nil;
}
}
我终于安顿下来了
[dictInfoForThisBusiness[@"Building"] nilIfNull]
,如果我期待NSString,它会起作用。是否有更好或更标准的方式?
答案 0 :(得分:3)
第一步是尝试摆脱所有其他陈述。简单地将此设置(?)方法更改为类似的方法会使其更具可读性:
BusinessToSave.numberOfLike = @(0);
if ([dictInfoForThisBusiness[@"LikeNumber"] isNotEmpty]) {
BusinessToSave.numberOfLike =dictInfoForThisBusiness[@"LikeNumber"];
}
BusinessToSave.numberOfDislike =@(0);
if (dictInfoForThisBusiness[@"DislikeNumber"]){
BusinessToSave.numberOfDislike =dictInfoForThisBusiness[@"DislikeNumber"];
}
BusinessToSave.buildingName =nil;
if([dictInfoForThisBusiness[@"Building"] isNotEmpty]){
BusinessToSave.buildingName=dictInfoForThisBusiness[@"Building"];
}
BusinessToSave.Street =nil;
if([dictInfoForThisBusiness[@"Street"] isNotEmpty]){
BusinessToSave.Street=dictInfoForThisBusiness[@"Street"];
}
如何创建一个方法来为您提供正确的对象(或零):
BusinessToSave.buildingName = [self valueForDictKey:@"Building"];
您甚至可以使用两种(或更多种)不同的方法。 (stringForDictKey,integerForDictKey)等。
BusinessToSave.numberOfLike = [self integerForDictKey:@"LikeNumber"];
BusinessToSave.numberOfDislike = [self integerForDictKey: @"DislikeNumber"];
BusinessToSave.buildingName = [self stringForDictKey: @"Building"];
BusinessToSave.street = [self stringForDictKey @"Street"];
另外:我建议你为所有这些键制作一些#defines,这很容易拼错其中一个键名。 :)
BusinessToSave.numberOfLike = [self integerForDictKey:KEY_LIKES];
BusinessToSave.numberOfDislike = [self integerForDictKey: KEY_DISLIKES];
BusinessToSave.buildingName = [self stringForDictKey: KEY_BUILDING];
BusinessToSave.street = [self stringForDictKey KEY_STREET];