NSObject why is alloc declared in both NSObject and NSProxy yet retain is in the NSObject protocol

StackOverflow https://stackoverflow.com/questions/7168884

  •  11-01-2021
  •  | 
  •  

Question

retain is declared in NSObject protocol.

Therefore NSObject class and NSProxy class implement it.

yet both NSProxy and NSObject classes both have an alloc.

Why isnt alloc declared in NSObject protocol?

Side question: NSObject protocol is also used to stored the class version of a method where as the instance method is in NSObject class. Is there anything to stop both class and instance being declared in the NSObject protocol. Why split them up?

@protocol NSCopying

- (id)copyWithZone:(NSZone *)zone;     //INSTANCE METHOD version of copyWithZone

@end
@interface NSObject <NSObject> {
    Class   isa;
}
...

+ (id)copyWithZone:(NSZone *)zone;     //CLASS METHOD version of copyWithZone

Cheers

Was it helpful?

Solution

I think this is determined by what is required by Objective-C, and what is required by implementation.

In order to create an object, you need a way to allocate it. This is done by the alloc method. Since this is required to use objective-c, it is implied that all root objects should implement it. However, memory management does not have to be done through reference counting. You could use garbage collection instead. Because of this, the retain method is not required to use objective-c. Apple's implementation created the retain method as a form of memory management. They wanted to ensure that all objects had it available, so they added it to the NSObject protocol. All root classes in Cocoa are supposed to conform to that protocol, so they should all have a retain method.

A class can conform to the NSCopying protocol to show that instances of that class can be copied. Normally, you wouldn't want to copy a class, so a class method isn't defined there. However, sometimes you don't know whether an object is a class or instance, but calling conformsToProtocol: will return the same value either way. By making an identically named class method, you know that it is safe to call copyWithZone: even if you don't know whether you have an instance or class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top