0

As we all know, factory methods can't call instance methods. Why does the code below work?

// .m file implementation DemoClass
// custom instance init method
- (instancetype)initWithDate:(NSDate *)date {
    if (self = [super init]) {
        self.lastTime = date;
    }
    return self;
}
// custom factory method
+ (instancetype)DemoClassWithDate:(NSDate *)date
    //here calling instance method initWithDate:
    return [[self alloc] initWithDate:date];
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jack.Ma
  • 1
  • 1

2 Answers2

3

[self alloc] will return an instance. initWithDate is just an instance method. No reason why a class method wouldn't be allowed to call an instance method on an instance.

PS. I would highly recommend that you check your compiler settings and tell the compiler to give you a warning if the result of '=' is used as a boolean value. This will prevent many hard to find bugs. You'll have to change the if to

if ((self = [super init]) != nil)
gnasher729
  • 51,477
  • 5
  • 75
  • 98
2

Because it has a reference to the, newly created, instance:

return [[self alloc] initWithDate:date];
//      ^^^^^^^^^^^^
//       reference
trojanfoe
  • 120,358
  • 21
  • 212
  • 242