开发者

where do I instantiate my class so I can access it throughout my app?

I've been working through some objective-c/ iOS dev books and I've hit a stumbling block. I get the feeling that I'm missing something dumb here, so I'm sure you guys can help, because you're all so damn smart :-).

I've got a very simple app that consists of 1 button and 1 label. Pushing the button puts a message in the label. I've created a class that includes a method to create said message. Here is the problem:

#import "classTestViewController.h"

@implementation classTestViewController
@synthesize myLabel;

- (void)viewDidLoad
{


}

-(IBAction) pressGo:(id)sender{

    MyClass * classTester = [[MyClass alloc] init];
    classTester.count = 15;
    NSString *newText = [classTester makeString ]; 
    myLabel.text = newText;
}
- (void)dealloc
{
    [classTester release];
    [myLabel release];
    [super dealloc];
}

The output of this app, in my label, is "Yay 15". So you can see the problem, the only way I can get this to work is to instantiate the class right there, in the "pressGo" method. This isn't desirable because another method can't access or change the class variable count. Also I get a warning that local declaration of classTester hides instance variable. If I move the class instantiation to the viewDidLoad method, which seems right, the other methods can't access it anymore.

#import "classTestViewController.h"

@implementation classTestViewController
@synthesize myLabel;

- (void)viewDidLoad
{
   开发者_运维知识库MyClass * classTester = [[MyClass alloc] init];


}

-(IBAction) pressGo:(id)sender{

    classTester.count = 15;
    NSString *newText = [classTester makeString ]; 
    myLabel.text = newText;
}
- (void)dealloc
{
    [classTester release];
    [myLabel release];
    [super dealloc];
}

The output of that is nada. If I try to access just one variable, classTester.count, for example, even after setting it, I get a 0 value. I also get the override warning here as well.

So my question is, how can i get access to that class instance throughout my app and not just in one method? I'm using a view based application.


Declare classTester in your interface file with:

@class MyClass
@interface classTestViewController : UIViewController
{
    MyClass *classTester;
}
// Any other custom stuff here
@end

Then instantiate it in your viewDidLoad method with:

classTester = [[MyClass alloc] init];

And you should be able to access the ivar from any method within this class. If you want it to be accessible to your entire app, @Waqas link will point you in the right direction.


You need to create a singleton class which instantiate once and is available inside whole project

Have a look

http://projectcocoa.com/2009/10/26/objective-c-singleton-class-template/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜