iOS中创建Model的最佳实践记录

2020-01-21 07:23:18于丽

很显然这解决上一种第一个缺点,但是还是有一个不足之处:

  • 如果字典没有某个属性对应的key的时候会崩溃,编译器并不能帮助我们排查这种运行时的崩溃。
  • 不能很好的满足某些时候只需要Model的某些property的需求。

    Mutable subclass

    我们看看Improving Immutable Object Initialization in Objective-C关于这个是怎么描述的

    We end up unsatisfied and continue our quest for the best way to initialize immutable objects. Cocoa is a vast land, so we can – and should – steal some of the ideas used by Apple in its frameworks. We can create a mutable subclass of Reminder class which redefines all properties as readwrite:

    
    @interface MutableReminder : Reminder <NSCopying, NSMutableCopying>
    
    @property (nonatomic, copy, readwrite) NSString *title;
    @property (nonatomic, strong, readwrite) NSDate *date;
    @property (nonatomic, assign, readwrite) BOOL showsAlert;
    
    @end

    Apple uses this approach for example in NSParagraphStyle and NSMutableParagraphStyle. We move between mutable and immutable counterparts with -copy and -mutableCopy. The most common case matches our example: a base class is immutable and its subclass is mutable.