OBJECTIVE-C 2.0 adds the class extensions to solve two problems:
Allows an object to have a private interface and can be validated by the compiler.
Supports a public read-only, private writable property.
Private Interface (privately Interface)
Before Objective-c 2.0, to define a private function, you would typically declare a "private" category in the implementation file:
@interface MyClass (Private)
-(ID) Awesomeprivatemethod;
@end
However, the private method of a class is often expected to be implemented in the @implementation block of the class, rather than in a separate @implementation block, as in the above category method. In fact, the category merely compensates for the objective-c lack of public/private limits.
The real problem is that the Objective-c compiler will assume that the methods declared in the category will be implemented elsewhere, so the compiler will not try to verify that they are actually implemented. In other words, the method that the developer declares may not be implemented, and the compiler will not have any warning. The compilation will assume that they will be implemented elsewhere or in separate files.
With class exteionsion, the implementation of the methods and properties declared in it will be placed in the @implementation chunk of class. Otherwise, the compiler will make an error.
[CPP] view Plaincopyprint?
//SOMECLASS.M
@interface SomeClass ()
-(void) extend;
@end
@implementation SomeClass
//All declarations are implemented in the header file or in the parent class of the method
//or some private functions
-(void) Extend {
//Implement Private method here;
}
@end
public readable, privately writable attributes (Publicly-readable, privately-writeable properties)
A common benefit of implementing an immutable (immutable) data structure is that external code cannot modify the state of an object with a setter. However, you might want it to be a writable property inside. Class extensions can do this: in a public interface (the declaration of a Class), the developer can declare that a property is read-only and is then declared writable in the class extension. In this way, the property will be read-only for external code, but the internal code can use its setter method.
[CPP] view Plaincopyprint?
@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
look similar, in fact different
Class extension are often misunderstood as an anonymous category. Their syntax is indeed very similar. Although all can be used to add methods and properties to an existing class, their purpose and behavior are different.
This article is from the "just finished a movie" blog, please be sure to keep this source http://9527606.blog.51cto.com/9517606/1617600
The use of extension and category in Objective-c