Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

KVC and OC dictionaries

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

KVC (key-value coding) is very similar to OC dictionaries in that they are key-value stores. But the OC dictionary is more flexible, it is a mapping.

[dict setObject: forKey:]

Int main (int argc, const charchar * argv [])

{

@ autoreleasepool

{

NSMutableDictionary * dict= [[NSMutableDictionary alloc] init]

[dict setObject: @ "1a23" forKey: [NSNumber numberWithInt:123]]; / / [NSNumber numberWithInt:123] is stored in the constant area (heap, stack, constant, register, code area, global area)

NSLog (@ "yvision% @", [dict objectForKey: [NSNumber numberWithInt:123]])

}

Return 0

}

The output is

2015-01-30 10 4015. 677 Test [12481 303] y:1a23

KVC does not need to be a dictionary object call, it comes from the classification of NSObject. @ interface NSObject (NSKeyValueCoding)

The advantage of KVC is that one of the non-public member variables added to ClassA does not set the getter method or the setter method. But as users, we can use KVC when we have to get or change this member variable. But the premise is that our key must be a member variable of ClassA. Or report a mistake.

@ interface ClassA: NSObject

{

@ private

NSNumber* _ x

}

@ property (nonatomic,retain,readonly) NSNumber* x

@ end

# import "ClassA.h"

Int main (int argc, const charchar * argv [])

{

@ autoreleasepool

{

ClassA * a = [[ClassA alloc] init]

[a setValue: [NSNumber numberWithInt:123] forKey:@ "x"]

/ / [a setValue: [NSNumber numberWithInt:123] forKey:@ "y"]; no member variable y, error reported

NSLog (@ "x% @", [a valueForKey:@ "x"])

}

Return 0

Output as

2015-01-30 11 0015 37 687 Test [12583 1 03] x 12 3

You can see that even private member variables can be set and changed even if there is no setter function. New waterway training

KVC can make changes preferentially through the setter and getter functions. If there are no setter and getter functions, get the member variables directly to make changes.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report