开发者

iPhone - How to access global variable with one class to another

I am new to iPhone devlopment.

I have a iphone app with 2 classes in it..( namely mainView,subView)

In the mainView , i have a global variable named currentId

i set the value for the currentId as 5.

Now what i need to know is how can i acce开发者_JS百科ss that currentId into the subView class.

Please help guide me out...


Ok I think some part of the answerer here is correct but we need to add something more here..

So I will go step by step

1 Definitely u need to make currentID as the property in MainView as stated by other answerers

2 As for Sudhanshu's answer , If u alloc and init mainview , a new viewcontroller will be initialised and hence its currentID will any value any value, so that is not correct.

3 Now for the solution part:- There are two solutions for this :-

(1) mainview* vc = (mainview*)self.parentViewController;

then access currentID as vc.currentId

Dont forget to import "mainview.h" in ur subview

(2) use appdelegate variables i.e. declare currentID in ur appdelegate and make it as a property

then set currentID in mainview as :-

urAppDelegate delegate = (urAppDelegate)[[UIApplication sharedApplication]delegate]; delegate.currentID=@"5";

and access in subview as

urAppDelegate delegate = (urAppDelegate)[[UIApplication sharedApplication]delegate]; NSLog(@"%@",delegate.currentID);

Dont forget to import "urAppDelegate.h" in both viewcontrollers


@barbgal ....you can access your variable currentid in the subview.......my making object of the mainView in the you subview class

Lets suppose your currentid variable is of type NSInteger...

mainView.h

NSInteger currentID;
@property(nonatomic,assign) NSInteger currentID;

mainView.m

 @synthesize currentID;
    currentID = 5; 
 //as you want to assign 5 to it

Now in your subView class made the object of the mainView class

eg:- mainView *mainView = [[mainView alloc]initWithNibName:@"mainView"bundle:nil];

Now assign it anywhere in your subView class as mainView.currentid......Do what u want to do with this currentid in the subView class


for accessing currentId you need to make it a property then by making the object of mainView class in subView class you can acces the currentID.

in mainView.h

NSInteger currentID;

@property(nonatomic,assign) NSInteger currentID;

in mainView.m

@synthesize currentID;

and set its value where you want and in subView make object of mainView class and by using . operator you can access this prperty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜