1

I want to make the following object accessable by all my code functions "public".

SomeObj *myobject = [[SomeObj alloc]init];

Please note that I have initialized the object inside interface by the following code , but i dose not work

Someobj *myobj;

But when I use alloc init , its work fine but I dont know how to access the myobj from another function , such as

- void runcar() {
       Cars *mycar = [[Cars alloc]init];
       [mycar run];
}

My question how I can stop the car from another function ??

Hima
  • 1,249
  • 1
  • 14
  • 18
qamooos
  • 93
  • 6
  • Possible duplicate of [Objective-C - Where are class instances declared?](http://stackoverflow.com/questions/35188058/objective-c-where-are-class-instances-declared) – Hamish Feb 10 '16 at 09:43

1 Answers1

-1

Define it in your interface:

@interface Cars ()
@property Cars *mycar;
@end

Then initialize it in your init function:

@implementation Cars

- (instancetype)init
{
    if ((self = [super init])) {
         _mycar = [[Cars alloc]init];
    }
    return self;
}

@end

Now you can use _mycar everywhere within your class. Define it in your header file if you want to use it public.

Jörn Buitink
  • 2,906
  • 2
  • 22
  • 33
  • Hello thank u , can u tell me what is the (instancetype) , its variable name or method name ??? – qamooos Feb 10 '16 at 07:59
  • Well, it is the type of the instance you created - modern objective c: https://developer.apple.com/library/ios/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html – Jörn Buitink Feb 10 '16 at 08:00
  • 1
    "Now you can access `_mycar` **everywhere** within your class" - if you want an instance variable you should declare one, if you want a property you should declare one and access it as `self.mycar` so the getter & setter are used and KVO works, declaring a property but using it as an instance variable is not a good choice. – CRD Feb 10 '16 at 08:20
  • Also, I hope you realise this code will lead to a cycle. You're creating a new `Cars` instance within the `Cars` initialiser.... – Hamish Feb 10 '16 at 12:38