Search code examples
ioskvc

KVC is not working


I am trying very simple KVC on iOS to learn.

#import <Foundation/Foundation.h>
@interface KVC : NSObject
@property (nonatomic,strong)NSString *string;
@end

In .m file

@implementation KVC
@synthesize string=_string;
@end

in main

int main(int argc, char *argv[])
{
    KVC *kvc;
    [kvc setValue:@"tunvir" forKey:@"name"];
    NSLog(@"%@",[kvc valueForKey:@"name"]);
}

I am expecting "tunvir" in console but it return null! Thanks


Solution

  • You will have to allocate and initialize the object. And you defined the property with a name string so you should use that name not the name

    int main(int argc, char *argv[])
    {
        KVC *kvc;
        kvc = [[KVC alloc] init];
        [kvc setValue:@"tunvir" forKey:@"string"];
        NSLog(@"%@",[kvc valueForKey:@"string"]);
    }