Skip to content

Concerns about init not being called, and allocWithZone being misused as a singleton, in the iOS Obj-c code #855

@chrishulbert

Description

@chrishulbert

Hi all,

I've been trying to delve into RNCallKeep to understand some things, and came across this which I thought might be worth bringing to your attention:

RNCallKeep *callKeep = [RNCallKeep allocWithZone: nil];

  • In setup, it calls 'alloc' but does not 'init'.
  • This is not the way things are done in Obj-C, according to Apple "You must use an init... method to complete the initialization process": https://developer.apple.com/documentation/objectivec/nsobject/1571958-alloc
  • allocWithZone is just there for historical reasons, idiomatically this is not to be called, alloc is what should be called.

Delving further, it appears someone has overridden allocWithZone to implement a singleton:

+ (id)allocWithZone:(NSZone *)zone {

  • This is confusing and un-idiomatic: allowWithZone isn't to be used, alloc is
  • Also alloc is about allocating new memory, not about managing singletons.

May I suggest a more idiomatic way to implement a singleton in objc is the following:

+ (instancetype)sharedInstance {
    static MySingleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

Please note the importance of calling 'init' in the above singleton.

I did place a breakpoint in 'init' but just got a callstack of incomprehensible RN C++ - I don't know what's calling this, and it concerns me that this is not being done properly.

Any chance that this could be improved? I could raise a PR but if so i'd love the feedback of the authors as to how this is (or if it is?) actually being inited currently and how to fix that too, or we might end up initing twice somehow.

Thanks all :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions