Question

I have custom class object that contains user object in it:

@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;
@property (nonatomic, retain) User *User
- (NSMutableDictionary *)toNSDictionary;
...
- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    return dictionary;
}

In toNSDictinary function I didn't mapped User object.
What is a good way to convert object to nsdictionary in situation like this?

Was it helpful?

Solution

Modify your toNSDictionary method:

- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    NSMutableDictionary *userDictionary = [NSMutableDictionary dictionary];
    [userDictionary setValue:self.User.someProperty1 forKey:@"someProperty1"];
    [userDictionary setValue:self.User.someProperty2 forKey:@"someProperty2"];
    [dictionary setValue:userDictionary forKey:@"User"];

    return dictionary;
}

OTHER TIPS

- (NSMutableDictionary *)toNSDictionary
{

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];

NSMutableDictionary *userDictionary = [NSMutableDictionary dictionary];
[userDictionary setValue:self.User.someProperty1 forKey:@"someProperty1"];
[userDictionary setValue:self.User.someProperty2 forKey:@"someProperty2"];
[dictionary setObject:userDictionary forKey:@"User"];

return dictionary;
}

while setting a dictionary for key try using

[dictionary   setObject: forKey: ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top