Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Applications in Objective-C runtime mechanism     - Single-node Hadoop installation notes distributed pseudo & (Server)

- to install the deployment of LVS under CentOS 7.0 (Server)

- Ubuntu 14.04 Configuring cuda-convnet (Linux)

- OpenNMS separate database (Server)

- Android Get App version number and version name (Programming)

- Install Ubuntu text editor KKEdit 0.2.10 (Linux)

- Install Python 3.3.4 under CentOS 6.4 (Linux)

- Linux set the maximum number of open files nofile and nr_open, file-max Description (Linux)

- Linux linux system security (Linux)

- Fast Sort Algorithms (Programming)

- The minimum initial use of the Linux operating system RancherOS feelings (Linux)

- Workaround CentOS error message during compilation PHP5 common (Linux)

- Install Kali Linux via PXE network (Linux)

- Java Set and List in the relationship and difference (Programming)

- Computer security perimeter recommendations (Linux)

- Java8 Lambda expressions and flow operations (Programming)

- Linux kernel IPv6 protocol closed manner (Linux)

- VMware Workstation virtual machine cloning (Linux)

- Practical Handbook: 130+ improve the efficiency of commonly used commands Vim (Linux)

- Python objects (Programming)

 
         
  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:      
 
- The difference between Objective-C language nil, Nil, NULL, NSNull (Programming)
- Linux --- file descriptors and redirection (Linux)
- Modern Objective-C syntax and new features (Programming)
- Linux operating system security management skills notes (Linux)
- Pydev installed and configured on the Eclipse (Linux)
- Several reasons MySQL garbled (Database)
- PHP interview questions of design patterns (Programming)
- Object Oriented Programming Java reflection (Programming)
- Python Flask environment to build (Linux)
- CentOS7 installation configuration Redis-3.0.0 (Database)
- Installation Sublime Text 3 (Build 3065) text editor in Ubuntu (Linux)
- Upload the project to GitHub, synchronous remote repository Github (Linux)
- About Samba certification process and permissions (Linux)
- Linux operating system boot manager -GRUB (Linux)
- Lua non-blocking write log (Programming)
- On the PC goes heavy security watch your startup items (Linux)
- How do I upgrade to Ubuntu 15.04 (Beta) (Linux)
- init level settings for Linux / etc / inittab file into six (restart) or does not support the level of solution (Linux)
- CentOS 7 How to install MySQL Server (Database)
- Comparison of C # and Java (Programming)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.