views:

61

answers:

1

AutoMapper for .Net lets you map from one type to another. Its most basic function is to create one type of class from another type of class by copying property values from type A that exist in type B (have matching names and types).

Example:

public class ClassA {
    public string StringProp { get; set; }
    public int IntProp { get;set; }
}
public class ClassB {
    public string StringProp { get; set; }
    public int SomeIntProp { get; set; }
}

ClassA classAInstance = new ClassA { StringProp = "Test", IntProp = 5 };
ClassB classBInstance = Mapper.Map<ClassA, ClassB>(classAInstance);

// This creates a new instance of ClassB and sets its StringProp property to "Test".
// It does not set the property on ClassB called "SomeIntProp" because there is no
// property on ClassA called "SomeIntProp"

Is there anything like this for Objective-C?

+1  A: 

You can use Key-Value Coding for this if you really, really want to, but I'd consider strongly why you might want to do such a thing in the first place.

To do it with Key-Value Coding, use -dictionaryWithValuesForKeys: and -setValuesForKeysWithDictionary: to do so. They're documented in the NSKeyValueCoding Protocol Reference.

Chris Hanson
Marked this as a solution since it does take care of part of the problem, I'll still have to build an array of keys using class_copyPropertyList. Based on your first sentence it sounds like you think this is a bad idea, any particular reason? I want to do this to create dumbed-down view models for multiple views from a single type of NSManagedObject without having to map the individual properties manually.
George
Why do you want to use "view models" rather than just use the model objects directly?
Chris Hanson
Also, if you're dealing with managed objects, you shouldn't use class_copyPropertyList; you can just ask an object's entity what its (modeled) properties are, and get its descriptions of its attributes, relationships, and fetched properties.
Chris Hanson
It's a responsibility/structure preference. I could definitely use the domain entities directly, but since there's usually a mismatch between what a view needs to display and what exists on a particular entity, as well as formatting to worry with, I prefer to load whatever entities needed to display the view and pass those off to a factory that returns a view model class representing everything I need to display in the view. Helps keep controllers simple and readable. It can result in a lot of mapping code that's boring/tedious, an automatic mapping utility helps with this.
George
PS-Thanks for the tip on inspecting managed objects.
George