TheElements:https://developer.apple.com/library/ios/samplecode/TheElements/Introduction/Intro.html.
是app的官方示例代碼.今天拜讀了之后,把一些收獲寫下來.
這個項目非常規(guī)范的使用了 apple 推薦的 MVC 模式做為代碼設(shè)計模式.面向?qū)ο蟮乃枷胍策\用的淋漓盡致.代碼邏輯非常的清晰,雖然代碼量并不是很大,代碼也不是很復(fù)雜,但是我覺得它的代碼習(xí)慣,封裝的思想都值得學(xué)習(xí).然后把一些值得說一說的代碼拿出來寫點東西.
雖然增加了一些類的文件,但是代碼層次更加的清晰明了,一個數(shù)據(jù)處理的類,然后把數(shù)據(jù)分發(fā)下去.感覺很順暢.
為了代碼的簡潔明了,這個項目創(chuàng)建了一個遵守 TableViewdataSource 的類來管理tableview的數(shù)據(jù)源.因為還需要遵守 ElementsDataSource ,所以自定義屬性覆蓋系統(tǒng)的 dataSource.
@interface ElementsTableViewController : UITableViewController
@property (nonatomic,strong) id<ElementsDataSource, UITableViewDataSource> dataSource;
ElementsDataSource 是一個協(xié)議,主要是用來自定義不同數(shù)據(jù)源的 tableview 的不同配置.
@protocol ElementsDataSource <NSObject>
@required
// these properties are used by the view controller
// for the navigation and tab bar
@property (readonly) NSString *name;
@property (readonly) NSString *navigationBarName;
@property (readonly) UIImage *tabBarImage;
// this property determines the style of table view displayed
@property (readonly) UITableViewStyle tableViewStyle;
// provides a standardized means of asking for the element at the specific
// index path, regardless of the sorting or display technique for the specific
// datasource
- (AtomicElement *)atomicElementForIndexPath:(NSIndexPath *)indexPath;
@optional
// this optional protocol allows us to send the datasource this message, since it has the
// required information
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
@end
自定義的ElementsSortedByAtomicNumberDataSource 遵守UITableViewDataSource 就可以做為 tableview 的數(shù)據(jù)源了.
@import UIKit;
#import "ElementsDataSourceProtocol.h"
@interface ElementsSortedByAtomicNumberDataSource : NSObject<UITableViewDataSource,ElementsDataSource>{
@end
這種dataSource 單獨一個類的方式不適合 cell 有交互需求的.
其中一個給對象排序的類值得一說
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptors = @[nameDescriptor];
[(self.nameIndexesDictionary)[aKey] sortUsingDescriptors:descriptors];
要對數(shù)組中的對象進行排序,而數(shù)組中含有多個對象,要根據(jù)對象的其中一個屬性進行排序的時候,就可以把這個屬性做為 NSSortDescriptor 的 Key , 把數(shù)組重新排列.
關(guān)于這個對象的用法在下面的推薦拓展閱讀里面說的非常全面.