gpt4 book ai didi

objective-c - 为什么更改字典中包含的可变数组不需要更新字典?

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:24 25 4
gpt4 key购买 nike

我正在尝试 CS193P 类(class) (Objective-C) 中的一段代码。我注意到编译器的工作方式。一个名为 photosNSMutableArray 被添加到一个 NSMutableDictionaryphotosByPhotographer。后来,对 photos 进行了更改,但未对 photosByPhotographer 进行任何更改。当我登录 photosByPhotographer 时,更改会自动应用到它,不需要任何额外的代码行!

我想知道编译器是如何做到这一点的?有什么 Material 可以阅读吗?

代码如下:

- (void)updatePhotosByPhotographer
{
NSMutableDictionary *photosByPhotographer = [NSMutableDictionary dictionary];
for (NSDictionary *photo in self.photos) {
NSString *photographer = [photo objectForKey:FLICKR_PHOTO_OWNER];
NSMutableArray *photos = [photosByPhotographer objectForKey:photographer];
if (!photos) {
photos = [NSMutableArray array];
[photosByPhotographer setObject:photos forKey:photographer];
NSLog(@"photosByPhotographer in if: %@", photosByPhotographer);
}
[photos addObject:photo];
NSLog(@"photosByPhotographer after if: %@", photosByPhotographer);
}
self.photosByPhotographer = photosByPhotographer;
}

NSLog()结果如下:

2012-07-20 20:05:57.618 Shutterbug[453:f803] photosByPhotographer in if: {
Dowbiggin = (
);
}

2012-07-20 20:05:57.620 Shutterbug[453:f803] photosByPhotographer after if: {
Dowbiggin = (
{
accuracy = 16;
context = 0;
dateupload = 1342836026;
description = {
"_content" = "";
};
farm = 9;
"geo_is_contact" = 0;
"geo_is_family" = 0;
"geo_is_friend" = 0;
"geo_is_public" = 1;
id = 7612787270;
isfamily = 0;
isfriend = 0;
ispublic = 1;
latitude = "37.307085";
longitude = "-121.900395";
originalformat = jpg;
originalsecret = 052e70d412;
owner = "22751315@N05";
ownername = Dowbiggin;
"place_id" = cils8sJUV7MeXHwt9A;
secret = 4437007c99;
server = 8161;
tags = "square squareformat iphoneography instagramapp uploaded:by=instagram foursquare:venue=49f13597f964a5209c691fe3";
title = "My little goofball";
woeid = 55971033;
}
);
}

最佳答案

那是因为在 Cocoa 中,您使用的是对象并通过引用传递。

想象一下这段代码:

NSMutableArray *a, *b;

a = [NSMutableArray new];
[a addObject:@"A"]; // a contains @"A"
b = a; // b is assigned to the same object
[b addObject:@"B"]; // a and b contain @"A", @"B"

NSLog(@"a = %p and b = %p", a, b); // same values

变量ab 指向 同一个对象。您还可以通过比较指针值看到这一点。

但是,如果我们执行以下操作:

NSMutableArray *a, *b;

a = [NSMutableArray new];
[a addObject:@"A"]; // a contains @"A"
b = [[a mutableCopy] autorelease]; // b is assigned to a COPY of the object
[b addObject:@"B"]; // b contains @"A", @"B", while a still contains @"A"

NSLog(@"a = %p and b = %p", a, b); // NOT the same values

b 被分配给 a 的副本(不是原始的),因此 b 指向另一个对象。您可以通过比较对象的地址来检查。

关于objective-c - 为什么更改字典中包含的可变数组不需要更新字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595303/

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