看apple的官方示例代码TheElements

TheElements:https://developer.apple.com/library/ios/samplecode/TheElements/Introduction/Intro.html.
是app的官方示例代码.今天拜读了之后,把一些收获写下来.

这个项目非常规范的使用了 apple 推荐的 MVC 模式做为代码设计模式.面向对象的思想也运用的淋漓尽致.代码逻辑非常的清晰,虽然代码量并不是很大,代码也不是很复杂,但是我觉得它的代码习惯,封装的思想都值得学习.然后把一些值得说一说的代码拿出来写点东西.

虽然增加了一些类的文件,但是代码层次更加的清晰明了,一个数据处理的类,然后把数据分发下去.感觉很顺畅.

为了代码的简洁明了,这个项目创建了一个遵守 TableViewdataSource 的类来管理tableview的数据源.因为还需要遵守 ElementsDataSource ,所以自定义属性覆盖系统的 dataSource.

@interface ElementsTableViewController : UITableViewController

@property (nonatomic,strong) id<ElementsDataSource, UITableViewDataSource> dataSource;

ElementsDataSource 是一个协议,主要是用来自定义不同数据源的 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 的数据源了.


@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];

要对数组中的对象进行排序,而数组中含有多个对象,要根据对象的其中一个属性进行排序的时候,就可以把这个属性做为 NSSortDescriptor 的 Key , 把数组重新排列.

关于这个对象的用法在下面的推荐拓展阅读里面说的非常全面.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,196评论 4 61
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,314评论 30 472
  • 今晚,失眠。 回想初识,美妙。 一起的经历,坎坷。 漫长的过程,坚定。 然而 当一切顺理成章后,彼此厌恶。 初识时...
    腊月绿阅读 1,176评论 0 0
  • 孩子说每天要在电脑上听一个故事,手机听叔叔讲一个故事(群里4号叔叔),再听我讲一个故事,阅读形式多样化呀。 ...
    7d1132dd053f阅读 1,462评论 0 0
  • 怎么区分主音,上主音,中音,下属音,属音?##### 所谓主音、上主音之类的,是音乐中乐音的乐名。乐名就是根据某一...
    观茉阅读 57,008评论 0 7