首页 > 代码库 > NSArray和NSMutableArray
NSArray和NSMutableArray
//1. NSArray EOItems *eOItems = [[EOItems alloc] init]; eOItems.ID = [NSNumber numberWithInt:1]; NSArray *arr = [NSArray arrayWithObjects:eOItems, nil]; eOItems.ID = [NSNumber numberWithInt:2]; NSLog(@"eOItems.ID =%@, ((EOItems *)[arr objectAtIndex:0]).ID=%@", eOItems.ID, ((EOItems *)[arr objectAtIndex:0]).ID); //打印结果: eOItems.ID =2, ((EOItems *)[arr objectAtIndex:0]).ID=2 EOItems *eOItems2 = [arr objectAtIndex:0]; eOItems2.ID = [NSNumber numberWithInt:22]; NSLog(@"eOItems2 =%@, ((EOItems *)[arr objectAtIndex:0]).ID=%@", eOItems2.ID, ((EOItems *)[arr objectAtIndex:0]).ID); //打印结果: eOItems2 =22, ((EOItems *)[arr objectAtIndex:0]).ID=22 NSLog(@"eOItems.ID =%@", eOItems.ID); //打印结果:eOItems.ID =22 //由此可见: NSArray只是存储对象的索引并没有真正复制对象, 对象由始至终只有一个 //2.NSMutableArray NSMutableArray *mutableArray = [arr mutableCopy]; ((EOItems *)[mutableArray objectAtIndex:0]).ID = [NSNumber numberWithInt:333]; NSLog(@"eOItems.ID=%@", eOItems.ID); NSLog(@"eOItems2.ID=%@", eOItems2.ID); NSLog(@"((EOItems *)[mutableArray objectAtIndex:0]).ID=%@", ((EOItems *)[mutableArray objectAtIndex:0]).ID); //输出结果 //eOItems.ID=333 //eOItems2.ID=333 //((EOItems *)[mutableArray objectAtIndex:0]).ID=333 //经NSArray mutableCopy得来的 NSMutableArray, 对象也始终只有一个 NSMutableArray *mulArr = [NSMutableArray array ]; EOItems *mulItems = [[EOItems alloc] init]; mulItems.ID = [NSNumber numberWithInt:111]; [mulArr addObject:mulItems]; ((EOItems *)[mulArr objectAtIndex:0]).ID = [NSNumber numberWithInt:222]; NSLog(@"mulItems.ID=%@, ((EOItems *)[mulArr objectAtIndex:0]).ID=%@",mulItems.ID, ((EOItems *)[mulArr objectAtIndex:0]).ID); //输出结果 //mulItems.ID=222, ((EOItems *)[mulArr objectAtIndex:0]).ID=222 mulItems.ID = [NSNumber numberWithInt:333333]; NSLog(@"mulItems.ID=%@, ((EOItems *)[mulArr objectAtIndex:0]).ID=%@",mulItems.ID, ((EOItems *)[mulArr objectAtIndex:0]).ID); //输出结果 //mulItems.ID=333333, ((EOItems *)[mulArr objectAtIndex:0]).ID=333333
总结: NSArray和NSMutableArray区别在于后者可变可以添加,删除,修改
他们存储的都是对象的引用
EOItems *item1 = [[EOItems alloc] init]; item1.ID = [NSNumber numberWithInt:1]; EOItems *item2 = [[EOItems alloc] init]; item2.ID = [NSNumber numberWithInt:2]; EOItems *item3 = item1; NSLog(@"item3.ID=%@", item3.ID); item3 = item2; NSLog(@"item3.ID=%@", item3.ID);
NSArray和NSMutableArray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。