Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Applications in Objective-C runtime mechanism     - Elaborate .NET Multithreading: Concepts (Programming)

- How Vim playing a mature IDE (Linux)

- Linux iptables: basic principles and rules (Linux)

- Ubuntu will be written in a command file, executable file, source command (Linux)

- JavaScript basic types and type conversion (Programming)

- Ubuntu 14.10 Server configuration wireless Internet access (Server)

- How to add and delete bookmarks in Ubuntu (Linux)

- C language files update in real time (Programming)

- Linux serial debugging tools xgcom install (Linux)

- When Linux Detailed time zone and common function of time (Linux)

- Source Analysis: Java object memory allocation (Programming)

- Oracle 11g RAC root.sh execution error second node failure example (Database)

- Spring + Log4j + ActiveMQ remote logging - Analysis of combat (Server)

- Linux Security and Optimization (Linux)

- The difference between vi and nano (Linux)

- SecureCRT session buffer size settings (Linux)

- Python type way of comparison (Programming)

- How to compile and install wxWidgets in Ubuntu / Debian / Linux Mint (Linux)

- How to make a U disk to install Ubuntu (Linux)

- Android Studio Installation and Configuration Guide tutorial (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:      
 
- RealVNC Server 5.2.3 Installation and Configuration In Fedora (Server)
- Build Eclipse + Maven + Scala-IDEA the Scala Web development environment (Server)
- numpy and SciPy installation under Python for scientific computing package (Linux)
- RabbitMQ user roles and access control (Linux)
- To use slay kill user processes (Linux)
- Under Ubuntu on how to use iptables firewall (Linux)
- CentOS install video converter FFmpeg and cutting tools segmenter (Linux)
- The best known for archiving / compression tool under linux (Linux)
- Common Linux System Troubleshooting (Linux)
- Red Flag Linux Desktop 6.0 hard disk installation guide (Programming)
- When a software RAID data recovery and reconstruction of how failure (Linux)
- B-tree - ideas and implementation of C language code (Programming)
- WinSCP to transfer text files will automatically convert the format (Linux)
- Java memory area Explanation (Programming)
- Linux mention the right notes (Linux)
- Nginx server security configuration (Server)
- Linux protobuf-c (Linux)
- Linux prohibit non-WHEEL user su command Detail (Linux)
- Linux system components Detailed log (Linux)
- KVM installation under CentOS 5.5 (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.