一般来说,我对代码很陌生,而且我正在学习 Objective-C,所以如果我错误地表达了这个问题,我提前道歉。
考虑到这个目标,我创建了几个数组:
显示有多少人并说出他们的名字
显示有多少个城市并说出它们的名字
将人员分配到城市并计算人口
我已经完成了这项任务,但我已将每个人分别分配到每个城市的数组中。有没有一种方法可以简单地关联 NSStrings?例如“blockCity = bill, bob, jim”而不是为人口创建一个新数组?
// My people
NSString *bill = (@"Bill");
NSString *bob = (@"Bob");
NSString *jim = (@"Jim");
NSString *kevin = (@"kevin");
NSString *stacy = (@"stacy");
NSString *cooper = (@"Cooper");
NSMutableArray *people = [NSMutableArray arrayWithObjects: bill, bob, jim, kevin, stacy, cooper, nil];
NSLog(@"Here are my people: %@", people);
NSLog(@"I have %lu people", [people count]);
// My places
NSString *blockCity = (@"BlockCity");
NSString *hyperCity = (@"HyperCity");
NSString *pixelTown = (@"PixelTown");
NSString *nowhere = (@"Nowhere");
NSMutableArray *cities = [NSMutableArray arrayWithObjects: blockCity, hyperCity, pixelTown, nowhere, nil];
NSLog(@"Cities: %@", cities);
NSLog(@"There are %lu cities", [cities count]);
//populations
// BlockCity population
NSMutableArray *bcpop = [NSMutableArray arrayWithObjects: bill, bob, jim, nil];
if ([bcpop count] == 0) {
NSLog(@"%@ is abandoned.", blockCity);
} else {
NSLog(@"%@ has a population of %lu", blockCity, [bcpop count]);
}
//HyperCity population
NSMutableArray *hcpop = [NSMutableArray arrayWithObjects: nil];
if ([hcpop count] == 0) {
NSLog(@"%@ is abandoned.", hyperCity);
} else {
NSLog(@"%@ has a population of %lu", hyperCity, [hcpop count]);
}
//PixelTown population
NSMutableArray *ptpop = [NSMutableArray arrayWithObjects: kevin, stacy, cooper, nil];
if ([ptpop count] == 0) {
NSLog(@"%@ is abandoned.", pixelTown);
} else {
NSLog(@"%@ has a population of %lu", pixelTown, [ptpop count]);
}
//Nowhere population
NSMutableArray *npop = [NSMutableArray arrayWithObjects: nil];
if ([npop count] == 0) {
NSLog(@"%@ is abandoned.", nowhere);
} else {
NSLog(@"%@ has a population of %lu", nowhere, [npop count]);
}