Ios 创建NSMutableArray对象
向NSMutableArray添加对象时遇到问题。我清楚地在typeList数组中放置了2个对象,但计数只显示为1。我做错了什么 内容.hIos 创建NSMutableArray对象,ios,objective-c,arrays,nsmutablearray,Ios,Objective C,Arrays,Nsmutablearray,向NSMutableArray添加对象时遇到问题。我清楚地在typeList数组中放置了2个对象,但计数只显示为1。我做错了什么 内容.h @interface TBContentModel : NSObject +(NSMutableArray*)typeList; +(void)setTypeList:(NSMutableArray*)str; 内容 static NSMutableArray *typeList = nil; @implementation TBContentMod
@interface TBContentModel : NSObject
+(NSMutableArray*)typeList;
+(void)setTypeList:(NSMutableArray*)str;
内容
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];
请减少示例中的代码量,并突出问题所在。减少代码。我是初学者,所以我不确定什么代码与问题相关。@Sancho您应该删除
setTypeList:
方法。好的。行。我假设你建议这样做是因为现在没有理由设置,因为我可以直接向其中添加对象。在进行你建议的编辑后,它似乎向数组中添加了两次相同的对象,而不是两个对象。虽然显示已添加了两个对象,但两个对象是相同的。有什么想法吗?@Sancho你检查过array
的内容,看看处理过的JSON是什么样子的吗?对象正确地进入了数组,但在for循环完成后,所有对象都被设置为最后一个进入的对象。根据一些研究,它似乎将数组中的所有对象都指向*测试。也许我没有正确初始化*测试?