cool hit counter How to access private variables in ios_Intefrankly

How to access private variables in ios


Write a TestObject class with the following code TestObject.h

#import <Foundation/Foundation.h>

@interface TestObject : NSObject

@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *sex;

@end

TestObject.m

#import "TestObject.h"
#import <objc/runtime.h>

@interface TestObject()

@property (copy, nonatomic) NSString *privateName;
@property (copy, nonatomic) NSString *privateSex;

@end

@implementation TestObject


@end

Approach I Using the KVC Approach

    TestObject *obj = [TestObject new];
    [obj getIvars];
    
    [obj setValue:@"123" forKey:@"privateName"];
    NSLog(@"privateName:%@", [obj valueForKey:@"privateName"]);

Mode II. Suppose we don't know what properties the TestObject has, so we can use RunTime to get all the properties

- (void)getIvars
{
    unsigned int count = 0;
     // Copy out the list of member variables for the hu
    Ivar *ivars = class_copyIvarList([self class], &count);
    
    for (int i = 0; i<count; i++) {
         // Fetching member variables
        Ivar ivar = ivars[i];
         // Print the names of member variables
        NSLog(@"%s---", ivar_getName(ivar));
         // Print the data type of member variables
        NSLog(@"%s---", ivar_getTypeEncoding(ivar));
        NSLog(@"---------------------------------------");
    }
     // Release
    free(ivars);
}

If we want to access the privateName property, the code is as follows

   unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([TestObject class], &count);
    // Changes to private variables
    Ivar privateNameIvar = ivars[2];
    object_setIvar(obj, privateNameIvar, @"456");
    NSString *privateName = object_getIvar(obj, privateNameIvar);
    NSLog(@"privateName : %@",privateName);

Demo:https://github.com/destinyzhao/GetAttributesAndMethod


Recommended>>
1、Can you tell whats trending in mobile phones this year If the Meizu 15 Plus can keep up itll be hard not to catch fire
2、Earth Hour guards the planet with artificial intelligence GDT and you can start a 60 life together
3、Concepts you must understand before developing for ethereum
4、Cocoon Revised Edition below
5、The countrys first selfdriving taxi university city trial operation 12 yuan to start waiting for you to experience

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号