2

我正在尝试将一些数据存储在NSMutableArray. 这是我的结构:

typedef struct{
    int time;
    char name[15];
}person;

这是添加一个人的代码:

person h1;
h1.time = 108000;
strcpy(h1.name, "Anonymous");
[highscore insertObject:[NSValue value:&h1 withObjCType:@encode(person)] atIndex:0];

所以,我尝试以这种方式提取:

NSValue * value = [highscore objectAtIndex:0];
person p;
[value getValue:&p];
NSLog(@"%d", p.time);

问题是最终的日志没有显示 108000!
怎么了?

4

3 回答 3

2

您的代码看起来正确(并且对我有用),所以我推断您没有初始化highscore. 因此,当您向它发送insertObject:atIndex:消息时,什么也没有发生。然后,当您将objectAtIndex:方法发送给它时,您将得到 nil 。当你发送getValue:到 nilNSValue *value时,它什么也不做,所以你person p的内存被随机堆栈垃圾填满,这就是你NSLog不打印 108000 的原因。

于 2012-07-06T17:01:01.147 回答
1

正如我最初的评论中所说,很少有理由用纯 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>
于 2012-07-06T16:24:04.120 回答
0

将 Person 重新实现为 Objective-C 对象并获得以下好处:

人.h:

@interface Person : NSObject
{
    int _time;
    NSString *_name;
}

@property (assign, nonatomic) int time;
@property (retain, nonatomic) NSString *name;

@end

人.m:

#import "Person.h"

@interface Person
@synthesize time = _time;
@synthesize name = _name;

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        // Add init here
    }
    return self;
}

- (void)dealloc
{
    self.name = nil;
    [super dealloc];
}

@end
于 2012-07-06T16:16:55.643 回答