I have a very simple TableViewController. I’m only implementing the data source methods and two other methods to modify the data source. The table’s dataSource array is an array retrieved from the @"dataSource key in TableViewController’s NSDictionary property classData. I’m probably over thinking this, which is the best way to use dataSource array in my TableViewController:
1) Define a property in .h and set the property to the dictionary’s @"dataSource key in viewDidLoad
@property (strong, nonatomic) NSMutableArray *dataSource;
2) Define the variable in .m interface
@interface TableViewController () {
NSMutableArray *dataSource;
}
@end
3) Create an instance of the array in every method I need it
NSMutableArray *dataSource = [self.classData objectForKey: @"dataSource"];
I’m leaning towards option 2 because none of the classes in my app need access to the array. However, option 3 keeps it encapsulated even further. I would like to know the correct approach for this simple situation.
The decision between option 1 and 2 is pretty easy to resolve: it all depends on whether your
datasourceshould be public or private; if it is private, then go with option 2.On the other hand, option 3 does does not seem really a good option (if either 1 or 2 is).
If your
datasourceis meant to be a local variable (i.e., a variable whole lifecycle is bound by the containing method runtime), then it is fine; but in this case you would not even think of declaring that variable as an instance variable.You declare a variable as instance variable when you need to share its value across multiple calls to some methods of the declaring class (even the same method called at different times). This will decide if the variable is local or instance.
If you mean using a
staticglobal variable whose scope is limited to the declaring method, then this is only superficially appealing. Indeed, the issue with it is that you cannot exactly foresee the use that will be required ofdatasourcein the future: it may be the case that you will need to access it – for whatever reasons – from another method, then that design would not adapt itself.More generally speaking, in terms of encapsulation, I think that in OOP, the correct level of encapsulation is the class level, IMO. This would also rule out again option 3.