1

我想将响应转换为NSDictionary. 响应是ALRegistrationResponsehttps://github.com/AppLozic/Applozic-Chat-iOS-Framework/blob/master/Applozic/DomainClasses/ALRegistrationResponse.m)的实现。

NSDictionary *_response = @
{
    @"message":[response message] != nil ? [response message] : [NSNull null],
    @"deviceKey":[response deviceKey] != nil ? [response deviceKey] : [NSNull null],
    @"userKey":[response userKey] != nil ? [response userKey] : [NSNull null],
    @"contactNumber":[response contactNumber] != nil ? [response contactNumber] : [NSNull null],
    @"lastSyncTime":[response lastSyncTime] != nil ? [response lastSyncTime] : [NSNull null],
    @"currentTimeStamp":[response currentTimeStamp] != nil ? [response currentTimeStamp] : [NSNull null],
    @"brokerURL":[response brokerURL] != nil ? [response brokerURL] : [NSNull null],
    @"imageLink":[response imageLink] != nil ? [response imageLink] : [NSNull null],
    @"statusMessage":[response statusMessage] != nil ? [response statusMessage] : [NSNull null],
    @"encryptionKey":[response encryptionKey] != nil ? [response encryptionKey] : [NSNull null],
    @"displayName":[response displayName] != nil ? [response displayName] : [NSNull null],
    @"notificationSoundFileName":[response notificationSoundFileName] != nil ? [response notificationSoundFileName] : [NSNull null]
};
4

3 回答 3

1

另一种可能性是将键用作选择器:

NSArray *keys = @[@"message", @"deviceKey", @"userKey", @"contactNumber", @"lastSyncTime", @"currentTimeStamp", @"brokerURL", @"imageLink", @"statusMessage", @"encryptionKey", @"displayName", @"notificationSoundFileName"];
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
for (NSString *key in keys) {
    SEL selector = NSSelectorFromString(key);
    [dict setObject:[response performSelector: selector] ?: [NSNull null] forKey:key];
}
于 2017-08-18T12:58:02.197 回答
1

以下语法至少更简洁:

NSDictionary *_response = @{
    @"message": [response message] ?: [NSNull null],
    @"deviceKey": [response deviceKey] ?: [NSNull null],
    @"userKey": [response userKey] ?: [NSNull null],
    @"contactNumber": [response contactNumber] ?: [NSNull null],
    @"lastSyncTime": [response lastSyncTime] ?: [NSNull null],
    @"currentTimeStamp": [response currentTimeStamp] ?: [NSNull null],
    @"brokerURL": [response brokerURL] ?: [NSNull null],
    @"imageLink": [response imageLink] ?: [NSNull null],
    @"statusMessage": [response statusMessage] ?: [NSNull null],
    @"encryptionKey": [response encryptionKey] ?: [NSNull null],
    @"displayName": [response displayName] ?: [NSNull null],
    @"notificationSoundFileName": [response notificationSoundFileName] ?: [NSNull null]
};
于 2017-08-18T12:19:23.820 回答
0

创建一个函数来检查 nil 怎么样?像这样的东西:

NSDictionary *_response = @
{
    @"message":checkForNil([response message])
],...
于 2017-08-18T12:50:52.830 回答