Get the App
SLTechnology News&Howtos  ›  Network Security  › 

KVC and OC dictionaries

Shulou Source: shulou.com Published: 2022-06-01 04:00:56 10月03日 Update

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.

Tags: Variables members dictionaries functions constants methods output similarity code user global premise benefit register object result coding channel if classification Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Technology MySQL MariaDB Redmi