正如我最初的评论中所说,很少有理由用纯 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>