Current location - Quotes Website - Personality signature - Why doesn't OC have an absolute private method?
Why doesn't OC have an absolute private method?
In object-oriented languages such as Java/C#, the access rights of methods can be controlled by public/private/protected. In OC, the method has no access modifier. There is no absolute private method in OC.

OC is a very dynamic language. Even if we write a private variable, we can still force it to be modified through KVC, which is still unsafe. Then, it is safe to write the property directly into a class extension called a class.

The meaning of denotation. After writing the class extension, KVC cannot access the property, but can access the method.

Due to the dynamic message mechanism of Objective-C, there is no real private method in OC. Private methods just don't have public documents, and they can also be called with runtime features.

Because: at compile time, even if this method is not declared in the header file, the compiler will compile the signature of the method into the method list of the class. When sending a message, it will automatically look up the message list, and if it finds a message with the same name, it will trigger.

Call private method:

SEL selector = NSSelectorFromString(@ " private method ");

object * ob =[[object alloc]init];

IMP IMP =[obmethodForSelector:selector];

typedefvoid (*func_t)(id,SEL);

func _ t func =(func _ t)imp;

Func(ob, selector);

//Private method:

- (void)privateMethod {

NSLog(@“private”);

}

Access and modify private variables:

[object setValue:@ " value " for key:@ " key "];