簡體   English   中英

關於Objective-C中的復制屬性

[英]About copy property in Objective-C

我測試了此示例代碼。

Sample.h

 {

    NSString *string1;
    NSString *string2;
    NSMutableString *string3;
}

@property (assign) IBOutlet NSWindow *window;
@property (strong,nonatomic) NSString *string1;
@property (copy,nonatomic) NSString *string2;
@property (strong,nonatomic) NSMutableString *string3;

@end

Sample.m

#import "Sample.h"

@synthesize string1;
@synthesize string2;
@synthesize string3;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    string1 = [[NSString alloc] init];
    string2 = [[NSString alloc] init];
    string3 = [[NSMutableString alloc] initWithString:@"test"];
    string2 = string3;
    string1 = string3;
    [string3 appendString:@"test"];
    NSLog(@"%@",string1);
    NSLog(@"%@",string2);
    NSLog(@"%@",string3);

}

@end

結果是

2012-09-23 00:11:48.610 sample[13468:303] testtest
2012-09-23 00:11:48.611 sample[13468:303] testtest
2012-09-23 00:11:48.611 sample[13468:303] testtest

我認為string2應該是“測試”,因為該屬性是副本。 但是string2是“ testtest”。

string2 = [string3 copy];

我認為這是結果。

string2 is "test"

為什么? 請告訴我,我睡不好覺。

問題在於您沒有訪問屬性,而是立即操作了后台實例變量。 對於這些ivars, =運算符不是特殊的, 並且不具有調用setter方法的效果 ,它只是常規的指針分配。 所以當你寫

string2 = string3;
string1 = string3

然后您將指向string3的指針分配給string1string2不管您對string3做什么,它也將對其他兩個變量有效,因為實際上它們指向的是同一字符串實例

您要做的是,一,將屬性聲明為copy而不是strong ,二,編寫

self.string2 = string3;
self.string1 = string3

為了調用setter方法並實際制作字符串的獨立副本。

P.s. 通過使用以下命令創建兩個NSString空實例

string1 = [[NSString alloc] init];
string2 = [[NSString alloc] init];

代碼,然后將其他內容重新分配給這些變量,您正在泄漏內存。

編輯:您很幸運,但您不幸運-通過使用ARC。 使用舊的運行時,您將浪費用戶RAM的寶貴字節。

但是還是。 您無需創建這些實例-您無需直接使用memcpy()將字符放入預分配的內存中。 在深入研究iOS開發之前,請閱讀有關C指針的綜合教程。

我不確定為什么您說string2屬性上的setter語義是copy 你宣稱它strong

您將NSString指針string2設置為NSMutableString指針string3。 然后,您繼續修改string3指向的可變字符串。 因此,您應該期望string2能夠反映出來。

順便說一下,這就是為什么您應該在具有可變對應項的對象上使用copy設置器語義的主要原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM