This chapter will be divided into two sections:
- The Set/get of KVC
- KVC Key-value path
The Set/get of KVC
There are 3 variables in Class A, all private permissions, and for access rights, see the OBJECTIVE-C member Variable "
A.h
@interface a:nsobject{@private *str; Nsinteger value; //Note there are no asterisks here oh oh *array;} @end
a.m.: Override the description function for NSLog
@implementation A /* * * */-(NSString *) description{return [nsstring stringWithFormat:@ "\n%@ \n%li\n%@", str, (long) value, array];} @end
MAIN.M: In theory, external variables are not accessible to these 3 private variables, but the KVC of violence comes.
A *a =[[A alloc] init];//set of KVC[A SetValue:@"HelloWorld"Forkey:@"Str"]; [A setvalue:@ -Forkey:@"value"]; [A setvalue:@[@"Hearthstone", @2] Forkey:@"Array"]; NSLog (@"%@", a);//KVC's GetNSString *str = [a valueforkey:@"Str"]; Nsinteger value= [[A Valueforkey:@"value"] IntegerValue];//ID to NsintegerNsarray *array = [a valueforkey:@"Array"]; NSLog (@"\n%@\n%ld\n%@", str, (Long) value, array);
Output to
HelloWorld
2015
(
Hearthstone,
2
)
HelloWorld
2015
(
Hearthstone,
2
)
Analysis:
KVC Set Method (emphasis)
[A setValue:@ "HelloWorld" forkey:@ "str"];
Is the set method of KVC, where key must be a property name for the message receiver, not a custom one.
Get method for KVC (focus)
NSString *str = [a valueforkey:@ "str"];
Is the Get method of KVC, where key must be a property name for the message receiver, and cannot be customized.
When the set method encounters a basic data type
[A setvalue:@ forkey:@ "value"];
Nsinteger is the basic data type, when setting the basic data type, you need to convert the basic type to NSNumber, when setting the value, the system will have the process of automatic unpacking, NSNumber will unpack the value of the assignment.
when the Get method encounters a base data type
Nsinteger value = [[a valueforkey:@ 'value'] integervalue]; // ID to Nsinteger
Valueforkey returns the ID type, the method of ID conversion to Nsinteger should be the above, and the following notation is wrong!
Nsinteger value = (nsinteger) [a valueforkey:@ "value"];
Off-topic: Rewrite description to facilitate NSLog output
-(NSString *) description{ return [nsstring stringWithFormat:@ "\n%@\n%li\n%@ ", str, (long) value, array];} NSLog (@ "%@", a);
Will print out
HelloWorld
2015
(
Hearthstone,
2
)
The KVC
Key-Value path
The KVC of Kvc/kvo's violence