Data Sources

来源:互联网 发布:中央电视网络直播 编辑:程序博客网 时间:2024/05/17 00:14

Data Sources

A data source is like a delegate, except that its methods supply the data for another object to display. The chief Cocoa classes with data sources are UITableView, UICollectionView, UIPickerView, and UIPageViewController. In each case, the data source must formally conform to a protocol with required methods.

It comes as a surprise to some beginners that a data source is necessary at all. Why isn’t a table’s data just part of the table? Or why isn’t there at least some fixed data structure that contains the data? The reason is that such an architecture would violate generality. Use of a data source separates the object that displays the data from the object that manages the data, and leaves the latter free to store and obtain that data however it likes (see on model–view–controller in Chapter 13). The only requirement is that the data source must be able to supply information quickly, because it will be asked for it in real time when the data needs displaying.

Another surprise is that the data source is different from the delegate. But this again is only for generality; it’s an option, not a requirement. There is no reason why the data source and the delegate should not be the same object, and most of the time they probably will be. Indeed, in most cases, data source methods and delegate methods will work closely together; you won’t even be conscious of the distinction.

In this simple example, we implement a UIPickerView that allows the user to select by name a day of the week (the Gregorian week, using English day names). The first two methods are UIPickerView data source methods; the third method is a UIPickerView delegate method. It takes all three methods to supply the picker view’s content:

- (NSInteger) numberOfComponentsInPickerView: (UIPickerView*) pickerView {

    return 1;

}


- (NSInteger) pickerView: (UIPickerView*) pickerView

        numberOfRowsInComponent: (NSInteger) component {

    return 7;

}


- (NSString*) pickerView:(UIPickerView*)pickerView

             titleForRow:(NSInteger)row

            forComponent:(NSInteger)component {

    NSArray* arr = @[@"Sunday",

                    @"Monday",

                    @"Tuesday",

                    @"Wednesday",

                    @"Thursday",

                    @"Friday",

                    @"Saturday"];

    return arr[row];

}

原创粉丝点击