gpt4 book ai didi

ios - 创建对象的 NSMutableArray

转载 作者:行者123 更新时间:2023-11-29 03:21:46 25 4
gpt4 key购买 nike

我在向 NSMutableArray 添加对象时遇到问题。我明明在 typeList 数组中放置了 2 个对象,但计数只显示为 1。我做错了什么?

内容.h

@interface TBContentModel : NSObject

+(NSMutableArray*)typeList;
+(void)setTypeList:(NSMutableArray*)str;

内容.m

static NSMutableArray *typeList = nil;

@implementation TBContentModel

- (id) init {
self = [super init];
if (self) {
typeList = [NSMutableArray array];
}
return self;
}

contentviewcontroller.m

@implementation TBViewController

- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jsonString = @"[{\"Content\":268,\"type\":\"text\"},{\"Content\":65,\"type\":\"number\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *dictionary in array)
{
TBContentModel *test = [[TBContentModel alloc] init];
test.type = dictionary[@"type"];
[[TBContentModel typeList] addObject:test];
NSLog(@"%@", test.type);
}
}

- (IBAction)tapButton:(id)sender {
NSLog(@"%d", [TBContentModel.typeList count]); // always shows 1
}

最佳答案

每次分配和初始化新的 TBContentModel 对象时,您都在重新创建静态 typeList 对象。

进行以下更改:

static NSMutableArray *typeList = nil;
static dispatch_once_t once;

+ (NSMutableArray*)typeList {
dispatch_once(&once, ^{
typeList = [NSMutableArray array];
});
return typeList;
}

并从 init 方法中删除以下行:

typeList = [NSMutableArray array];

关于ios - 创建对象的 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21002356/

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