如何在objective-c中的类之间粘贴值

时间:2010-08-02 23:34:05

标签: objective-c

如何在objective-c中的类之间粘贴值?

1 个答案:

答案 0 :(得分:2)

我将假设问题涉及一个类ClassOne,其中包含一个实例变量int integerOne,您希望从另一个类ClassTwo访问该类。处理此问题的最佳方法是在ClassOne中创建属性。在ClassOne.h中:

@property (assign) int integerOne;

这声明了一个属性(基本上,两个方法,- (int)integerOne- (void)setIntegerOne:(int)newInteger)。然后,在ClassOne.m中:

@synthesize integerOne;

这为你“合成”了两种方法。这基本上相当于:

- (int)integerOne
{
    return integerOne;
}

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

此时,您现在可以从ClassTwo调用这些方法。在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]);
}

听起来你应该通过一些教程来学习这些Objective-C概念。我建议these