2012-02-23 15 views
0

私はclass2で使う必要があるclass1に整数を持っています。 class2の.mファイルにclass1の.hファイルをインポートしましたが、変数にアクセスできません。なぜか分からない! :(別のクラスの変数へのアクセス

は私もクラス1の.hファイル内の各整数のプロパティを作成し、.mファイルでそれを合成した。

誰もが?

は基本的に、これは何をされ、問題が何であるかを知っています私はclass1.h

//interface here 
{ 
    NSInteger row; 
    NSInteger section; 
} 

@property NSInteger row; 
@property NSInteger section; 

であり、これは、Class1のための.mファイルである。

//implementation 
@synthesize section = _section; 
@synthesize row = _row; 

その後、class2の実装では、私はクラス2の方法では、これらの整数にアクセスするにはどうすればよいこの

#import "Class2.h" 
#import "Class1.h" 

がありますか?

+1

あなたはClass1 * aClass1Var = [[Class1 alloc] init]を試していますか? aClass1Var.intVal1 = 0;または単にClass1.intVal1 = 0; ? –

+0

@endの前にClass1.hに次の行を追加します。@property int myInt; '@implementationの後にClass1.mで「@synthesize myInt;」を追加します。 – 0xDE4E15B

+0

コードを含むように質問を編集しました – Hauwa

答えて

5

プロパティ(変数)にアクセスするには、class1のインスタンス(オブジェクト)を作成する必要があります。

// Create an instance of Class1 
Class1 *class1Instance = [[Class1 alloc] init]; 

// Now, you can access properties to write 
class1Instance.intProperty = 5; 
class1Instance.StringProperty = @"Hello world!"; 

// and to read 
int value1 = class1Instance.intProperty; 
String *value2 = class1Instance.StringProperty; 

編集

// Create an instance of Class1 
Class1 *class1Instance = [[Class1 alloc] init]; 

// Now, you can access properties to write 
class1Instance.row = 5; 
class1Instance.section = 10; 

// and to read 
NSInteger rowValue = class1Instance.row; 
NSInteger sectionValue = class1Instance.section; 
+0

どうすればいいのか教えていただけますか? – Hauwa

+0

yay!それを試してみました!できます!ありがとう! :D – Hauwa

+2

この答えがうまくいく場合は、チェックして(チェックして)@schに報酬を与える必要があります – zenopolis

0

私は(How can I access variables from another class?を見て)同様の問題のための答えを共有しました。しかし、私はここでそれを繰り返すことができます。

"XCode"では、インポートを行い、プロパティとして宣言してオブジェクトを作成し、次に "object.variable"構文を使用する必要があります。ファイル "Class2.m"は次のようになります。

#import Class2.h 
#import Class1.h; 

@interface Class2() 
... 
@property (nonatomic, strong) Class1 *class1; 
... 
@end 

@implementation Class2 

//accessing the variable from balloon.h 
...class1.variableFromClass1...; 

... 
@end 
関連する問題