Domanda

I am a newbie in Objective C, Xcode and so on. Thanks to your help, reading this forum, i did some steps in the right direction, but only in a "Single View Application".

Now I have in my storyboard two views:

(FirstViewController.h / m) (SecondViewController.h /m)

I also created an Objective C class whom is meant to receive data from those two views.

At first time, in the FirstViewController i had an IBA ACTION.

When a button was pressed:

controllo *control;
control = [[controllo alloc] init];

and then i use to set "control" instances using properties .. and It worked.

Now The same instance of "controllo" (control) should receive data even from my SecondViewClass, but I cannot access to it, even if the button of the first view (IBA ACTION) is pressed BEFORE passing to the second view.

Could you please show me how have a class accessible from all the views I need in my project?

Thanks!

È stato utile?

Soluzione

Put all your variables inside a class, access the class via singleton pattern, and import the class header into the prefix.pch file

example :

GlobalClass.h

#import <Foundation/Foundation.h>

@interface GlobalClass : NSObject

@property (nonatomic, strong) NSString *globalString;
@property (nonatomic, strong) NSNumber *globalNumber;

+ (GlobalClass*) sharedClass;

- (void) methodA;

@end

and in GlobalClass.m

#import "GlobalClass.h"

@implementation GlobalClass

+ (GlobalClass *)sharedClass {

 static GlobalClass *_sharedClass = nil;

 static dispatch_once_t oncePredicate;

 dispatch_once(&oncePredicate, ^{
     _sharedClass = [[GlobalClass alloc] init];
 });

 return _sharedClass;
}

- (id)init {
    self = [super init];
    if (self) {

    //init variable here

    }

    return self;
}

- (void) methodA {

   //do something here
   NSLog(@"this is methodA called");

}

@end

put this inside your .pch file in supporting files

#import "GlobalClass.h"

now you can access the global class variable from any class, by using :

[GlobalClass sharedClass].globalString = @"this is a global string";

you can also access the method, by using :

[GlobalClass sharedClass] methodA];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top