Similar to C ++, the use of public, protected, and private exists in objective-C, but the forms are different. Here is a brief summary. 1. @ public, @ protected, @ private I personally think that there is no clear difference between @ public and @ protected. If the objects within their scope are not set to @ property, the object is equivalent to the protected object, only the subclass and itself can access this object. If the object is set to @ property, the user can access this object. @ Private: As the name implies, private objects are declared here. Note: It can be accessed through pointers. 2. static object (within the class) We can declare an object outside the class "{" and "}", that is, it can be written together with the method and @ property to declare a static object inside the class. 3. Static Method When "+" is used to modify the method and declare it in the header file, it means that this method is equivalent to the static method in C ++ and called directly through the class. However, although such a method can be called directly through a class, it cannot be called through an object. 4. Public Method When "-" is used before the method and is declared in the header file, the method can be called through the class object. 5. Private Method In objective-C, the private method is implemented through category. In the implementation file, we declare the category of A Class. Here, the private method is used. Class objects cannot be called. Similarly, because the method is known in the class implementation file, subclass cannot override this method. The following code implements public, protected, and private. Header file # Import <Foundation/Foundation. h> @ Interface grammar: nsobject { @ Public Nsstring * publicstring;
@ Protected Nsstring * protectedstring;
@ Private Nsstring * privatestring; }Nsstring * staticstring; @ Property (nonatomic, retain) nsstring * publicstring; + (Void) staticmethod; -(Void) publicmethod; @ End Implementation File # Import "grammar. H" # Pragma mark- # Pragma mark grammar (private) @ Interface grammar (private) -(Void) privatemethod; @ End # Pragma mark- # Pragma mark Grammar @ Implementation Grammar @ Synthesize publicstring; -(ID) Init { If (Self = [Super init]) { If (publicstring = nil) { Publicstring = [[nsstring alloc] init]; }
If (protectedstring = nil) { Protectedstring = [[nsstring alloc] init]; }
If (privatestring = nil) { Privatestring = [[nsstring alloc] init]; }
If (staticstring = nil) { Staticstring = [[nsstring alloc] init]; } }
Return self; } -(Void) dealloc { [Publicstring release]; [Protectedstring release]; [Privatestring release];
[Super dealloc]; } # Pragma mark- # Pragma mark public Method + (Void) staticmethod { } -(Void) publicmethod { } # Pragma mark- # Pragma mark private Method -(Void) privatemethod { } @ End
The above is my understanding of public, protected, and private in objective-C. If there is any new understanding, it will be updated. |