【问题标题】:Creating Dictionary from a model that contains nil values从包含 nil 值的模型创建字典
【发布时间】:2013-07-13 23:03:37
【问题描述】:

我有以下型号:

@interface Person : NSObject

@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *middleName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, copy) NSString *favoriteMeal;
@property (nonatomic, copy) NSString *favoriteDrink;
@property (nonatomic, copy) NSString *favoriteShow;
@property (nonatomic, copy) NSString *favoriteMovie;
@property (nonatomic, copy) NSString *favoriteSport; 

-(NSDictionary *)getSomeInfo;
-(NSDictionary *)getAllInfo;

@end

第 1 部分: 我希望getSomeInfo 为所有不包含 nil 的字段返回 NSDictionary(例如 {"firstName", self.firstName})。我怎样才能做到这一点? (我可以检查每个值,但我想知道是否有更好的方法)

第 2 部分: 我希望getAllInfo 返回带有所有属性的 NSDictionary,如果一个包含 nil 则它应该抛出一个错误。再次我必须写一个很长的条件语句来检查还是有更好的方法?

注意:我想在不使用外部库的情况下执行此操作。我是这门语言的新手,所以如果在 Objective-C 中有更好的模式,我愿意接受建议。

【问题讨论】:

  • dictionaryWithVakuesForKeys:
  • 异常通常是为 Objective-C 中不可恢复的错误保留的(这意味着应该很快就会退出),这与 Java 和 Python 等语言不同。考虑使用 NSError 作为输出参数,甚至只是将字典中的值设为 [NSNull null]
  • @Kitsune 感谢您指出这一点,我会毫不犹豫地阅读更多相关信息。

标签: objective-c nsdictionary


【解决方案1】:

有两种方法。

1) 检查每个值:

- (NSDictionary *)getSomeInfo {
    NSMutableDictionary *res = [NSMutableDictionary dictionary];

    if (self.firstName.length) {
        res[@"firstName"] = self.firstName;
    }
    if (self.middleName.length) {
        res[@"middleName"] = self.middleName;
    }
    // Repeat for all of the properties

    return res;
}

2)使用KVC(键值编码):

- (NSDictionary *)getSomeInfo {
    NSMutableDictionary *res = [NSMutableDictionary dictionary];

    NSArray *properties = @[ @"firstName", @"middleName", @"lastName", ... ]; // list all of the properties
    for (NSString *property in properties) {
        NSString *value = [self valueForKey:property];
        if (value.length) {
            res[property] = value;
        }
    }

    return res;
}

对于getAllInfo 方法,您可以执行相同的操作,但如果缺少任何值,则返回nil。将nil 结果视为并非所有属性都有值的指示。

【讨论】:

  • 天哪!当我开始阅读有关 KVC 的内容时,我觉得这正是我想要的。它确实减少了很多样板代码。谢谢!
猜你喜欢
  • 2018-08-04
  • 2018-12-13
  • 1970-01-01
  • 2021-04-13
  • 2019-05-13
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多