NSMutableArray:添加和提取struct

时间:2012-07-06 15:15:35

标签: objective-c struct nsmutablearray nsvalue

我试图在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!
有什么问题?

3 个答案:

答案 0 :(得分:2)

您的代码看起来正确(并且对我有用),因此我推断您没有初始化highscore。因此,当您向其发送insertObject:atIndex:消息时,没有任何反应。然后,当您向其发送objectAtIndex:方法时,您将无法返回。当您将getValue:发送到零NSValue *value时,它什么都不做,因此您的person p会留下随机堆栈垃圾,这就是为什么您的NSLog无法打印108000

答案 1 :(得分: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>

答案 2 :(得分:0)

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

Person.h:

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

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

@end

Person.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