根据apple objective-c文档,NSObject使用C指针来跟踪它们.我对iOS很新,并且将NSObjects上的指针操作与C指针进行比较会让人感到困惑. 例如: NSString *string1 = @"This is a string";NSString *string2;string2
例如:
NSString *string1 = @"This is a string"; NSString *string2; string2 = string 1;
在C中,(如果我错了请纠正我)this = b / w 2指针使它们指向相同的“指针”.这意味着更改string1也应该更改string2.但它似乎没有像这样工作,并且NSStrings无论如何都是严格不变的,所以这增加了一些混乱.
string1 = @"new string";
如果这些指针像C指针一样操作,那么这不应该改变string2,因为它指向与string1相同的位置.此外,在C中,必须先将指针指定给指针对象才能取消引用.此规则似乎不适用于NSObjects.什么是’@’在做什么?最后,为什么我没有看到NSObjects的解引用发生如下:
*string1 = @"modifying the string"; //shouldn't this be how to access the contents of the pointer string1 if it operates like a c pointer?
有人可以对Objective-C指针下的内容以及它们与C指针的比较和对比有所了解吗?任何帮助将不胜感激.
您将在C中获得与Objective-C中相同的行为:如果您这样做char *a = "hello"; char *b = a; b = "world";
然后a不会改变.当对象可变时,对多个指针指向的公共对象所做的更改将变为可见. NSString和C字符串文字都不可变,所以让我们构建一个不同的例子:
NSMutableString *string1 = [NSMutableString string:@"This is a string"]; NSMutableString *string2; string2 = string1; NSLog(string1); NSLog(string2); [string1 appendString:@" (a very long one!)"]; NSLog(string1); NSLog(string2);
现在string2“看到”对string1所做的更改,因为该对象是可变的.
C中的类似示例如下所示:
char[] a = "hello"; char b = a; printf("%s %s\n", a, b); strcpy(b, "world"); printf("%s %s\n", a, b);