クラス1に整数値(テーブルビューのセル数)を保存するインスタンス変数があり、この変数を別のクラス(class2など)で使用したいのですが、どの構文を使用したかわかりませんか???
4 に答える
« 可能であればメンバー変数を使用します。
@interface MyClass : NSObject
{
int score;
}
@property (nonatomic, assign) int score;
@end
@implementation MyClass
@synthesize score;
@end
//access
MyClass *object = [MyClass alloc] init];
object.score = 99;
« NSUserDefault も使用できます
// Snippet used to save your highscore in the prefs.
int highScore = yourGameScore;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Snippet used to get your highscore from the prefs.
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
あなたは次のようにすることができます:
Class1
例: String を からに渡したいとしClass2
ます。
最初に Class2 に文字列を作成し、次のようにプロパティとして定義しますClass2.h
。
NSString *classTwoString;
@property (nonatomic, retain) NSString *classTwoString;
でClass2.m
:
@synthesize classTwoString;
次に、たとえば、ボタンClass1
がタッチされたときに文字列を渡したいとします。そのアクション ( create IBAction
、ボタンの にリンクtouchesUpInside
) で、2 番目のクラスのインスタンスを取得するように設定できます。次に例を示します。
Class2 *class2 = [[Class2 alloc] init];
class2.classTwoString= classOneString;
上記の方法をお勧めします。
使用NSUserDefaults
- アプリケーションがクラッシュすると、保存された値が失われる可能性があります。
おそらくプロパティを使用したいと思うでしょう。次に例を示します。
Class1.h
@property int myValue
Class1.m
self.myValue = 2
Class2.m
int v = instanceOfClass1.myValue
プロパティの使用に関するチュートリアルへのリンクは次のとおりです: http://www.raywenderlich.com/2712/using-properties-in-objective-c-tutorial
@implementation classA {
int v;
}
id x = [[classA alloc] init];
x->v = 123;
「目的の c インスタンス変数」をグーグルで検索し、この記事を見つけました。 http://blog.ablepear.com/2010/04/objective-c-tuesdays-instance-variables.html