0

I have simple example:

  1. NavViewController
  2. ViewController
  3. ViewController2

In ViewController:

#import "ViewController.h"
#import "ViewController2.h"

@interface ViewController ()

@end

NSArray *array;// Neither in @interface nor in @implementation 

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    array = [[NSArray alloc] initWithObjects:@"12345", nil];

    ViewController2 *vc = [[ViewController2 alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

In ViewConroller2:

#import "ViewController2.h"

@interface ViewController2 ()

@end

NSArray *array;

@implementation ViewController2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"%@",array);


}

I don't understand why my array in viewController2 passed data from viewController? Can explain this?

Guys I know how pass data to another viewController with property. I want to understand why, in this case, the data is transferred!

Rajesh
  • 10,318
  • 16
  • 44
  • 64
dev.nikolaz
  • 3,184
  • 3
  • 19
  • 32

2 Answers2

1

Because you've declared NSArray *array; as a Global variable. And, as long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.

we also declare global variables using extern

extern int GlobalVar;

Here, externtells the compiler that this is just a declaration that an object of type int identified by GlobalVar exists and linker's job to ensure.

In one of your source file, you could say

int GlobalVar = 7;

I believe this is the reason in your case.

Ajith Renjala
  • 4,934
  • 5
  • 34
  • 42
0

When you declare your variable outside @interface or @implementation it is considered to be static variable hence it worked. keep it inside would not work.

@interface ViewController ()
{
 NSArray *array;
}
@end

try this instead of your code

Rajesh
  • 10,318
  • 16
  • 44
  • 64
  • iDev, can u show explanation/manuals about statics variable, because I don't use static variables in my projects, and encountered for the first time – dev.nikolaz Aug 26 '14 at 14:04
  • By printing the description you would be able to get. Because both the class array description is same – Rajesh Aug 26 '14 at 14:07