views:

111

answers:

1

I have downloaded a sample code of AA-Plot Chart.

One of the .h files:

@interface MainViewController : UIViewController <APYahooDataPullerDelegate, CPPlotDataSource> {
    CPLayerHostingView *layerHost;
@private
    APYahooDataPuller *datapuller;
    CPXYGraph *graph;
}    
@property (nonatomic, retain) IBOutlet CPLayerHostingView *layerHost;
@end

In the .m file the interface is declared again?

@interface MainViewController()

@property(nonatomic, retain) CPXYGraph *graph;
@property(nonatomic, retain) APYahooDataPuller *datapuller;

@end

I found the above code in the sample project's main view controller code.

If I do the following, what will be the difference between above code and the below code?

@interface MainViewController : UIViewController <APYahooDataPullerDelegate, CPPlotDataSource> {
    CPLayerHostingView *layerHost;
    APYahooDataPuller *datapuller;
    CPXYGraph *graph;
}    
@property (nonatomic, retain) IBOutlet CPLayerHostingView *layerHost;
@property(nonatomic, retain) CPXYGraph *graph;
@property(nonatomic, retain) APYahooDataPuller *datapuller;
@end
+3  A: 

The "extra" stuff you're seeing in the .m file is a category. The original programmer probably just wanted to hide some of his implementation details from the public interface of his class (in the .h file), so he made a category (nameless in this case, which is why there's nothing inside the ()) to add them in his implementation file. In this specific case, he's hiding the accessors for his private variables so that external code can't get at them.

The changes you show in your second code snippet put everything into a single class interface. These changes shouldn't affect runtime operation at all. (Except you took out the @private, was that on purpose?) The semantic difference is that the category methods are added to the class at runtime.

Categories can add only methods, not instance variables, which is why the original code has all of the instance variable declarations (even those with the 'secret' accessors) in the original @interface block.

Carl Norum
I like your idea, 'secret' accession through category.
sugar
+1 This is a very common pattern in Cocoa programming. As you said, the internal category is used to hide the accessors from users of the class.
e.James
The () is actually a class extension, not a category. The syntax is similar to the category syntax, but it produces different output.
Peter Hosey