gpt4 book ai didi

objective-c - NSMutableArray:添加和提取结构

转载 作者:行者123 更新时间:2023-12-04 05:40:04 25 4
gpt4 key购买 nike

我正在尝试将一些数据存储在 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!
怎么了?

最佳答案

正如我在最初的评论中所说,很少有理由用纯 c 结构来做这种事情。而是使用真正的类对象:

如果您不熟悉下面的语法,您可能需要查看这些 ObjC 2.0 上的快速教程以及阅读 Apple 的文档:

  • A Quick Objective-C 2.0 Tutorial
  • A Quick Objective-C 2.0 Tutorial: Part II

  • 人物等级:
    // "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>

    关于objective-c - NSMutableArray:添加和提取结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11364987/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com