私の最初のコメントで述べたように、純粋な C 構造体でこの種のことを行う理由はめったにありません。代わりに、実際のクラス オブジェクトを使用します。
以下の構文に慣れていない場合は、ObjC 2.0 に関するこれらの簡単なチュートリアルを参照したり、Apple のドキュメントを読んだりすることをお勧めします。
人物クラス:
// "Person.h":
@interface Person : NSObject {}
@property (readwrite, strong, nonatomic) NSString *name;
@property (readwrite, assign, nonatomic) NSUInteger time;
@end
// "Person.m":
@implementation Person
@synthesize name = _name; // creates -(NSString *)name and -(void)setName:(NSString *)name
@synthesize time = _time; // creates -(NSUInteger)time and -(void)setTime:(NSUInteger)time
@end
クラスの使用:
#import "Person.h"
//Store in highscore:
Person *person = [[Person alloc] init];
person.time = 108000; // equivalent to: [person setTime:108000];
person.name = @"Anonymous"; // equivalent to: [person setName:@"Anonymous"];
[highscore insertObject:person atIndex:0];
//Retreive from highscore:
Person *person = [highscore objectAtIndex:0]; // or in modern ObjC: highscore[0];
NSLog(@"%@: %lu", person.name, person.time);
// Result: "Anonymous: 108000"
デバッグを簡単にするために、次のメソッドPerson
を実装することもできます。description
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ %p name:\"%@\" time:%lu>", [self class], self, self.name, self.time];
}
これにより、ロギングのためにこれを行うことができます:
NSLog(@"%@", person);
// Result: "<Person 0x123456789 name:"Anonymous" time:108000>