对于我的生活,我不能想到这一点。 appDelegate的employeeList数组正在更新,没有任何代码告诉它更新。更新发生在以下行之间:
[tabs chargeInterest:days];
和
[array addObject:tabs.detailItem];
线。因此,看起来好像更新发生在chargeInterest方法中,可以在下面看到。目标是防止appDelegate.employeeList完全不改变。
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1) {
if (buttonIndex == 1) {
NSString *password = [alertView textFieldAtIndex:0].text;
NSString *days = [alertView textFieldAtIndex:1].text;
if ([password isEqualToString:@"admin"]) {
NSMutableArray *array = [[NSMutableArray alloc] init];
ViewTab *tabs = [[ViewTab alloc] init];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
for (int g = 0; g < [appDelegate.employeeList count]; g++) {
id h = [appDelegate.employeeList objectAtIndex:g];
[tabs createDetailItem];
[tabs setDetailItem:h];
[tabs chargeInterest:days];
[array addObject:tabs.detailItem];
}
// Below tells the user whether or not any interest was charged.
float totalBefore = 0.0;
for (int x = 0; x < [appDelegate.employeeList count]; x++) {
id r = [appDelegate.employeeList objectAtIndex:x];
float tab = [[r tabTotal] floatValue];
totalBefore += tab;
}
float totalAfter = 0.0;
for (int y = 0; y < [array count]; y++) {
id s = [array objectAtIndex:y];
float tab = [[s tabTotal] floatValue];
totalAfter += tab;
}
}
}
}
}
从ViewTab类引用的两种方法
- (void)createDetailItem {
if (!self.detailItem) {
self.detailItem = [[Employee alloc] init];
}
}
- (void)chargeInterest:(NSString *)daysOld {
NSDate *now = [[NSDate alloc] init];
NSNumber *numSeconds = [NSNumber numberWithDouble:[now timeIntervalSinceReferenceDate]];
int currentSeconds = [numSeconds intValue];
int days = [daysOld intValue];
int secondsOld = days * 86400;
NSMutableArray *arr = [[NSMutableArray alloc] init];
float newTotal;
for (int a = 0; a < [self.detailItem.tab count]; a++) {
id b = [self.detailItem.tab objectAtIndex:a];
NSNumber *numSecsSince = [NSNumber numberWithDouble:[[b dateAdded] timeIntervalSinceReferenceDate]];
int secondsSince = [numSecsSince intValue];
int secondsBetween = currentSeconds - secondsSince;
if (secondsBetween > secondsOld) {
float price = [[b price] floatValue];
price *= 2;
[b setPrice:[NSNumber numberWithFloat:price]];
}
newTotal += [[b price] floatValue];
[arr addObject:b];
}
[self.detailItem setTab:arr];
NSNumber *num = [NSNumber numberWithFloat:newTotal];
[self.detailItem setTabTotal:num];
}
答案 0 :(得分:1)
考虑代码的这四行:
id h = [appDelegate.employeeList objectAtIndex:g];
[tabs createDetailItem];
[tabs setDetailItem:h];
[tabs chargeInterest:days];
甚至没有费心阅读chargeInterest
,我只是想让你规定这段代码肯定会 导致appDelegate.employeeList
内的变化。为什么?因为h
现在在appDelegate.employeeList
和tabs
之间共享;您通过获取h
元素获得了对appDelegate.employeeList
的引用,并将该引用交给了tabs
,因此可以自由地变异h
(假设h
的类型不是完全不可变的,例如NSString)。
这是真的任何时间两个对象共享对同一第三个对象的引用。他们中的任何一个都可以改变第三个对象。 Objective-C中对象的引用只是指针。因此,一个对象不能仅仅因为你有一个对它的引用而免于变异,因为有人 else 可能也引用它并对其进行变异。
如果您不希望这种情况发生,那么您需要设计一个不可变对象类型(如NSString等),否则您需要先复制该对象与别人分享。