Accessing a property from another class

后端 未结 3 1995
余生分开走
余生分开走 2021-01-29 13:52

Im trying to build an app where the user inputs a number at a textfield and after pressing the button another view shows up with the result of that input.

Each number th

3条回答
  •  隐瞒了意图╮
    2021-01-29 14:42

    As far as I understand your question, if you need a method returning the string title depending on the number provided you can make your method as a class method of your LibraryData class, not instance method, like:

    + (NSString *)titleStringFromInt: (NSInteger) intVal {
        if (intVal < 5000) 
            return @"Poor!";
        else
        return @"Rich!";
    }
    

    And call it from your controller like, [LibraryData titleStringFromInt: [[ViewController.fieldLabel text] intValue]];

    If you need to actually store data into your LibraryData class being accessible from all other controllers in your app, I would suggest taking into singleton pattern implementation.

    For example using blocks:

    + (LibraryData *)instance
    {
       static dispatch_once_t onceToken = 0;
    
       __strong static id _sharedObject = nil;
    
       dispatch_once(&onceToken, ^{
           _sharedObject = [[self alloc] init];
       });
    
       return _sharedObject;
    }
    

    And call it, like [LibraryData instance].number from your ViewController code. Anyway I think it's a good to move your if/else code out of getter method of your variable to some helper class method.

提交回复
热议问题