user3504848
user3504848

Reputation: 39

Initialize and Allocate a Class that is visible to all methods

Greetings i need to init alloc an instance of a class and have it accessible by any method

Example for using "Whatever *boom = [Wathever alloc]init];"

@interface something : NSObject;

@implementation

-(void) method1{

boom.size = 10;

}

-(void) method2{
boom.color = blue;
}

Where would i alloc and init boom so that i can manipulate it in every method?

Upvotes: 0

Views: 54

Answers (3)

bpapa
bpapa

Reputation: 21497

In a single class? Make it a property of that class.

//.h
@property Whatever *boom;

//.m
- (id)init {
   self = [super init];
   if (self) {
      _boom = [[Whatever alloc] init];
   }
   return self;
}

Across your whole app? Create an instance of it somewhere, like your app delegate, and then pass it along to the Root View Controller, which in turns passes it to each View Controller.

// AppDelegate .m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // app setup code

   Whatever *boom = [[Whatever alloc] init];
   FirstViewController vc = self.window.rootViewController;
   vc.boom = boom;
}

// FirstViewController.h, NextViewController.h, etc.
@property Whatever *boom;

// FirstViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
   NextViewController *nextVC = sender.destinationViewController;
   nextVC.boom = self.boom;
}

You could also go the Singleton route, but then you are tightly coupled to a single instance of the class app-wide.

Upvotes: 1

See when you create a class in that to intialize that class a common method will always be there which calls that class it self:

Something like this :

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

You can declare the instance in .h file like this :

Whatever *boom;

Than you can initialize that instance in above method as following :

-(id)init
{
   self = [super init];
   if (self)
   {
      boom = [Wathever alloc]init];
   }
   return self;
}

hope this will help you.

Upvotes: 0

Oswaldo Leon
Oswaldo Leon

Reputation: 261

for example in whatever.h and whatever.m to call the methods of a class must be declared in whatever.h

-(void) method1;
-(void) method2;

and used

Whatever *boom = [Wathever alloc]init];
[boom method1];
[boom method2];

Upvotes: 1

Related Questions