Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Applications in Objective-C runtime mechanism     - Memcached source installation and configuration under CentOS 6.6 (Server)

- Ubuntu 12.04 LTS installation configuration JDK1.6.0_45 (Linux)

- Xshell upload files to achieve Windows host Linux (Linux)

- tespeed - test speed of Python tools (Linux)

- Use window.name + iframe cross-domain access to data Detailed (Programming)

- Linux installed and tested the deployment of Kafka distributed cluster (Server)

- Approach the next Linux shared interrupts (Linux)

- In Debian 4.3 compiler under Linux-2.6.28 kernel Summary (Programming)

- How to run Kali Linux 2.0 in Docker container (Linux)

- SendMail version of Java implementation with attachments (Programming)

- Valgrind * not * leak check tool (Linux)

- How to build Mono 3.4.0 / 3.4.1 on Windows (Linux)

- Swift string common method (Programming)

- Spring Data MongoDB combat (Database)

- Cancel Root Command History under Linux (Linux)

- Java eight new features 8 (Programming)

- Sshuttle A VPN-based transparent proxy that uses ssh (Server)

- Oracle 11g em start newspaper site's security certificate has a solution to the problem (Database)

- Linux operating system boot process analysis (Linux)

- Ubuntu users how to install the latest Nvidia graphics drivers (Linux)

 
         
  Applications in Objective-C runtime mechanism
     
  Add Date : 2018-11-21      
         
       
         
  An acquaintance runtime

Objective-C is a dynamic language, so-called dynamic languages, at the time of program execution to dynamically determine the type of a variable, the variable corresponding to the type of execution method. Therefore, commonly used in Object-C string class mapping techniques to dynamically create class object. Due to the dynamic language features OC, we can by some means, variable runtime dynamically change object even approach, which is what we call the runtime mechanism.
 
Second, do you have any way to the operation of such variable it?

First, let's look at an example, here's one I created MyObject class:

//.h===========================
@interface MyObject: NSObject
{
    @private
    int privateOne;
    NSString * privateTow ;;
}
@end
// =============================
//.m===========================
@interface MyObject ()
{
    @private
    NSString * privateThree;
}
@end
@implementation MyObject
- (Instancetype) init
{
    self = [super init];
    if (self) {
        privateOne = 1;
        privateTow = @ "Tow";
        privateThree = @ "Three";
    }
    return self;
}
- (NSString *) description {
    return [NSString stringWithFormat: @ "one =% d \ ntow =% @ \ nthree =% @ \ n", privateOne, privateTow, privateThree];
}
@end
// =============================
 


This class is quite safe, first of all, in the header file does not provide any way to interface, we have no way to do anything to use dot syntax, privateOne and PrivateTow although two variables declared in the header file, but it is a private type, by way of pointers though we can see them, do not read any modification operation

He will tell us that this is a private variable, we can not use. For privateThree, we are helpless, not only can not be used, we do not see even its existence. So in this case, you have any way to manipulate these variables it? Yes, it is time to show the real technology: runtime!
 
Third, access to the object through the runtime variable list

        To operate the variable object, we first should have captured these variables, so that they have no place to hide. Whether declared in the header file or files to achieve, regardless of the type is public or private, as long as the declaration of this variable, the system will allocate space for it, we can capture it through runtime mechanisms, as follows:

#import "ViewController.h"
#import "MyObject.h"
// Header file contains runtime
#import < objc / runtime.h >
@interface ViewController ()
@end
@implementation ViewController
- (Void) viewDidLoad {
    [Super viewDidLoad];
    // We declare a pointer to unsigned int type, and assign memory
    unsigned int * count = malloc (sizeof (unsigned int));
    // Call the method runtime
    // Ivar: Object Content method returns the object here will return a pointer to type Ivar
    // Class_copyIvarList method can capture all the variables of the class, there will be a number of variables of unsigned int pointer
    Ivar * mem = class_copyIvarList ([MyObject class], count);
    // Traverse
    for (int i = 0; i <* count; i ++) {
        // Traversed by moving the pointer
        Ivar var = * (mem + i);
        // Get the name of the variable
        const char * name = ivar_getName (var);
        // Get the type of a variable
        const char * type = ivar_getTypeEncoding (var);
        NSLog (@ "% s:% s \ n", name, type);
    }
    // Release memory
    free (count);
    // Note Processing wild pointer
    count = nil;
}
- (Void) didReceiveMemoryWarning {
    [Super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
@end

It is not a small surprise a bit, regardless of where a variable, as long as it is, let it nowhere to hide.
 
Fourth, let me find you, let me change you!

        Only access to the variable name and type, and perhaps with no eggs, yes, we get variable purpose is not to watch, but to operate it, which the runtime, is also a trifle dish. Code is as follows:

- (Void) viewDidLoad {
    [Super viewDidLoad];
    // Get the variable
    unsigned int count;
    Ivar * mem = class_copyIvarList ([MyObject class], & count);
    // Create an object
    MyObject * obj = [[MyObject alloc] init];
    NSLog (@ "before runtime operate:% @", obj);
    // Set variable
    object_setIvar (obj, mem [0], 10);
    object_setIvar (obj, mem [1], @ "isTow");
    object_setIvar (obj, mem [2], @ "isThree");
    NSLog (@ "after runtime operate:% @", obj);
    
}

Tip: modifying int variable, you might encounter a problem under the ARC, the compiler will not allow you to assign a value of type int id, in buildset in Objective-C Automatic Reference Counting can be modified to No .

You can see, those variables are seemingly very safe we changed.
 
Fifth, let me see it your way

        We can get through runtime variable mechanism and to change the value, then we'll be bold enough to try those proprietary method, we first add some methods MyObject class, we only realize, do not declare them:

@interface MyObject ()
{
    @private
    NSString * privateThree;
}
@end
@implementation MyObject
- (Instancetype) init
{
    self = [super init];
    if (self) {
        privateOne = 1;
        privateTow = @ "Tow";
        privateThree = @ "Three";
    }
    return self;
}
- (NSString *) description {
    return [NSString stringWithFormat: @ "one =% d \ ntow =% @ \ nthree =% @ \ n", privateOne, privateTow, privateThree];
}
- (NSString *) method1 {
    return @ "method1";
}
- (NSString *) method2 {
    return @ "method2";
}

Such an approach is that we can not call out to them, and the idea of operating variables, we must first capture of these methods:

    // Get all member methods
    Method * mem = class_copyMethodList ([MyObject class], & count);
    // Iterate
    for (int i = 0; i         SEL name = method_getName (mem [i]);
        NSString * method = [NSString stringWithCString: sel_getName (name) encoding: NSUTF8StringEncoding];
        NSLog (@ "% @ \ n", method);
    }
 
Get the names of these methods, we can boldly call:

    MyObject * obj = [[MyObject alloc] init];
    NSLog (@ "% @", [obj method1]);

Tip: Here the compiler will not give us prompt method, boldly calls can be.
 
Six dynamic class add methods

        The most powerful part of the runtime mechanism to come, imagine, if we can dynamically add methods to the class, it would be a matter of how exciting things, note that this is a dynamic additions, and the biggest difference is that categories this is the only way to decide whether to add a run method.
 
- (Void) viewDidLoad {
    [Super viewDidLoad];
    // Add a new method, and the third parameter is the return value type of v is void, i is int ,: the SEL, and other objects are!
    class_addMethod ([MyObject class], @selector (method3), (IMP) logHAHA, "v");
    
    unsigned int count = 0;
    Method * mem = class_copyMethodList ([MyObject class], & count);
    for (int i = 0; i         SEL name = method_getName (mem [i]);
        NSString * method = [NSString stringWithCString: sel_getName (name) encoding: NSUTF8StringEncoding];
        NSLog (@ "% @ \ n", method);
    }
    
    MyObject * obj = [[MyObject alloc] init];
    // Run this method
    [Obj performSelector: @selector (method3)];
    
}
// Method to achieve
void logHAHA () {
    NSLog (@ "HAHA");
}

As can be seen from the front of the five elements, the method has been added to the list can be seen from the last row, you do not question.
 
Seven, do small hands and feet

Programmers always insatiable, and now we have to do something, be replaced by a function of our class out of the function:

- (Void) viewDidLoad {
    [Super viewDidLoad];
    MyObject * obj = [[MyObject alloc] init];
    // Replace previous methods
    NSLog (@ "% @", [obj method1]);
    //replace
    class_replaceMethod ([MyObject class], @selector (method1), (IMP) logHAHA, "v");
    [Obj method1];
    
}
void logHAHA () {
    NSLog (@ "HAHA");
}

The cool enough now, by this method, we can confuse the function of the system are set. Of course, runtime there are many very cool way:

id object_copy (id obj, size_t size)

A copy of an object

id object_dispose (id obj)

Releasing an object

const char * object_getClassName (id obj)

Get the object's class name

ive

void method_exchangeImplementations (Method m1, Method m2)
Swapping two methods
     
         
       
         
  More:      
 
- Construction CA certificate using OpenSSL command line (Server)
- CentOS system Amoeba + MySQL Master-slave configuration (Database)
- Ubuntu 14.04 compile and install Apache (Server)
- Github Getting Started Basic Course (Linux)
- Shell Programming Regular Expressions (Programming)
- Linux AS4 VPN server in conjunction with a firewall perfect (Linux)
- MongoDB 3.0 New Features (Database)
- Create a DLL using MinGW and Attention (Programming)
- High-performance JavaScript loops and flow control (Programming)
- Configuring a Linux operating system security management services (Linux)
- How Datadog monitor Nginx (Server)
- Repair Raspbian Encountered a section with no Package (Linux)
- Linux centralized log server rsyslog (Server)
- The most simple drive to write and test procedures under linux (Programming)
- Five programming fallacy (Programming)
- How x2g0 install Remote Desktop on Linux VPS (Server)
- Shuffle Process Arrangement in MapReduce (Server)
- Java String and StringBuffer and StringBuilder Comments (Programming)
- Spring3 + SpringMVC + Hibernate4 full annotation environment configuration (Server)
- MySQL and MariaDB new master from the cluster configuration GTID (Database)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.