-1

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!

Lundin
  • 195,001
  • 40
  • 254
  • 396
Funesto
  • 67
  • 1
  • 9

1 Answers1

1

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];
  • Thank You, Yuandra! :-) Now I can access to some global class variables, but ... how do I access to methods? I'd still need to create an instance of a class and use its methods in every view! – Funesto May 15 '14 at 18:03
  • You only need to add the method to your .h and .m file. I've updated my answer with example of method. – Yuandra Ismiraldi May 16 '14 at 13:13
  • Thank you ... I used + (void) methodA, but now I will use your suggestion. Thanks It really helped me! :-) – Funesto May 16 '14 at 13:56