Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 从包含零值的模型创建字典_Objective C_Nsdictionary - Fatal编程技术网

Objective c 从包含零值的模型创建字典

Objective c 从包含零值的模型创建字典,objective-c,nsdictionary,Objective C,Nsdictionary,我有以下型号: @interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *middleName; @property (nonatomic, copy) NSString *lastName; @property (nonatomic, copy) NSString *status; @property (nonatomi

我有以下型号:

@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中有更好的模式,我愿意接受建议。

有两种方法

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(键值编码):


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

请查看以启动或
dictionaryWithVakuesForKeys:
。与Java和Python等语言不同,Objective-C中的不可恢复错误通常会保留异常(意味着应该很快退出)。考虑使用NSerror作为OUT参数,或者甚至只是使字典中的值为<代码> [nSNURL NULL] 。@ KKSUNE谢谢您指出这一点,我将大胆地阅读更多关于它的内容。哦,伙计!当我开始阅读有关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;
}