Search code examples
objective-ciosxcoderestkit

Iterate over key values in a Restkit Model


I'm guessing there is a simple solution here, but I've tried some things and nothing seems to work out. What I'd like to do is be able to iterate through the stored values in a model so I can present them in different ways graphically.

I can access the web service and store the data perfectly. As part of a larger model, I have a goals model with various goals that can be set.

GoalsModel looks like

@class RoundGoalsModel;

@interface RoundGoalsModel : NSObject {

    NSNumber* _scoreGoal;
    NSNumber* _parsGoal;
    NSNumber* _birdiesGoal;
}

@property (nonatomic, retain) NSNumber* scoreGoal;
@property (nonatomic, retain) NSNumber* parsGoal;
@property (nonatomic, retain) NSNumber* birdiesGoal;

@end

All the data is in there as expected. Now all I need to do is figure out how to loop through the keys and values in the Model so I can do things like present different icons for different goals, check if a value is null, etc. I'm trying to avoid having to access each individually with a bunch of conditional statements.

I've tried casting it to an array and other things that dont seem to work. Any advice or suggestions pointing me in the right direction would be awesome. Thanks!


Solution

  • Your problem isn't a RestKit problem it's just an issue with your design. Since you already have your data placed into the individual fields you could just add a new field to return them in an array.

    .h

    @property(readonly, retain)NSDictionary *allProperties;
    

    .m

    @synthesize allProperties;
    
    - (NSDictionary*)allProperties
    {
       return [NSDictionary dictionaryWithObjectsAndKeys: _scoreGoal, @"scoreGoal", _parsGoal, @"parsGoal", _birdiesGoal, @"birdiesGoal", nil];
    }
    

    Then you could easily iterate over the dictionary and do whatever you want.