Key Paths

来源:互联网 发布:单机版数据库 编辑:程序博客网 时间:2024/06/09 21:02

A key path allows you to chain keys in a single expression. If an object is key–value coding compliant for a certain key, and if the value of that key is itself an object that is key–value coding compliant for another key, you can chain those keys by calling valueForKeyPath: and setValue:forKeyPath:. A key path string looks like a succession of key names joined using dot-notation. For example, valueForKeyPath:@"key1.key2" effectively calls valueForKey: on the message receiver, with @"key1" as the key, and then takes the object returned from that call and calls valueForKey: on that object, with @"key2" as the key.

To illustrate this shorthand, imagine that our object myObject has an instance variable theData which is an array of dictionaries such that each dictionary has a name key and a description key. I’ll show you the actual value of theData as displayed by NSLog:

(

    {

        description = "The one with glasses.";

        name = Manny;

    },

    {

        description = "Looks a little like Governor Dewey.";

        name = Moe;

    },

    {

        description = "The one without a mustache.";

        name = Jack;

    }

)

Then [myObject valueForKeyPath: @"theData.name"] returns an array consisting of the strings @"Manny", @"Moe", and @"Jack". If you don’t see why, review what I said a few paragraphs ago about how NSArray and NSDictionary implement valueForKey:.

原创粉丝点击