开发者

How do you past values between classes in objective-c

How do you past values between cla开发者_如何学运维sses in objective-c?


I'm going to assume the question involves a class, ClassOne, with an instance variable int integerOne, which you'd like to access from another class, ClassTwo. The best way to handle this is to create a property in ClassOne. In ClassOne.h:

@property (assign) int integerOne;

This declares a property (basically, two methods, - (int)integerOne, and - (void)setIntegerOne:(int)newInteger). Then, in ClassOne.m:

@synthesize integerOne;

This "synthesizes" the two methods for you. This is basically equivalent to:

- (int)integerOne
{
    return integerOne;
}

- (void)setIntegerOne:(int)newInteger
{
    integerOne = newInteger;
}

At this point, you can now call these methods from ClassTwo. In ClassTwo.m:

#import "ClassOne.h"
//Importing ClassOne.h will tell the compiler about the methods you declared, preventing warnings at compilation

- (void)someMethodRequiringTheInteger
{
    //First, we'll create an example ClassOne instance
    ClassOne* exampleObject = [[ClassOne alloc] init];

    //Now, using our newly written property, we can access integerOne.
    NSLog(@"Here's integerOne: %i",[exampleObject integerOne]);

    //We can even change it.
    [exampleObject setIntegerOne:5];
    NSLog(@"Here's our changed value: %i",[exampleObject integerOne]);
}

It sounds like you should walk through a few tutorials to learn these Objective-C concepts. I suggest these.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜