In objective-C 2.0, class extensions is added to solve two problems:
- An object can have a private interface and can be verified by the compiler.
- Supports a public read-only, private writable attribute.
Private Interface)
Before objective-C 2.0, to define a private function, you usually declare "private" category in the implementation file:
@ Interface myclass (private)
-(ID) awesomeprivatemethod;
@ End
However, the private method of the class is usually implemented in the @ implementation block of the class, rather than in the independent @ implementation block as the category method above. In fact, category only makes up for the lack of public/private restrictions in objective-C.
The real problem is that the objective-C compiler will think that the methods declared in category will be implemented elsewhere, so the compiler will not try to confirm whether they are actually implemented. That is to say, the methods declared by the developer may not be implemented, and the compiler will not give any warning. Compilation will assume that they will be implemented elsewhere or in an independent file.
Using class exteionsion, the implementation of the declared methods and attributes will be placed in the @ implementation block of the class. Otherwise, the compiler reports an error.
// Someclass. m @ interface someclass ()-(void) Extend; @ end @ implementation someclass // All implementations of Methods declared in header files or parent classes // or some private functions-(void) extend {// implement private method here;} @ end
Publicly-readable, privately-writeable Properties)
Implementing an immutable data structure usually has the advantage that external code cannot use setter to modify the object state. However, you may want it to be a writable attribute internally. Class extensions can do this: in public interfaces (class declaration), developers can declare an attribute to be read-only, and then declare it writable in class extension. In this way, this attribute is read-only for external code, but internal code can use its setter method.
@ Interface myclass: nsobject @ property (retain, readonly) float value; @ end // Private extension, hidden in the main implementation file. @ interface myclass () @ property (retain, readwrite) float value; @ end
Looks similar, but actually different
Class extension is often misunderstood as an anonymous category. Their syntax is indeed very similar. Although they can be used to add methods and attributes to an existing class, their purpose and behavior are different.
Refer to: Apple registration enation
Original article address:
Minutia on objective-C categories and extensions
Reprinted please indicate the source: http://blog.csdn.net/horkychen