【发布时间】:2010-04-06 08:34:44
【问题描述】:
有时我遇到的代码有 *,有时是 **。谁能解释他们在Objective C中的含义? (我曾经是一名 Java 程序员,有 C/C++ 方面的经验。)
【问题讨论】:
标签: objective-c programming-languages
有时我遇到的代码有 *,有时是 **。谁能解释他们在Objective C中的含义? (我曾经是一名 Java 程序员,有 C/C++ 方面的经验。)
【问题讨论】:
标签: objective-c programming-languages
* 表示您正在使用指向变量的指针,并且最常用于存储对 Objective-C 对象的引用,这些对象只能存在于堆上而不是堆栈上。
指针并不是 Objective-C 独有的一部分,而是 C 的一个特性(因此也是它的派生语言,Objective-C 就是其中之一)。
如果你质疑*和**之间的区别,第一个表示指针,而第二个表示指向指针的指针;后者相对于前者的优势在于,当在方法参数中使用** 传入对象时,方法可以更改此参数,并且可以在调用方法中访问新值。
也许 ** 在 Cocoa 中最常见的用法是在使用 NSError 对象时。当调用失败时可以返回NSError 对象的方法时,方法签名将如下所示:
- (id)someMethodThatUsesObject:(id)object error:(NSError**)error;
这意味着调用函数可以传入一个指向NSError对象的指针,但someMethodThatUsesObject:可以根据需要将error的值更改为另一个NSError对象,然后可以由调用方法访问。
这通常用作函数只能返回一个值这一事实的解决方法。
【讨论】:
bycopyonly;指针是传递方法的唯一方式byref;当您通过引用传递对象指针 (NSError *) 时,这需要双指针 (NSError **)。 (也就是说;对error 的值的本地修改不会被传递到调用者中;所以如果传入一个指向不可用对象的指针,那么,你就完蛋了。)
NSError*(而不是NSError**),那么someMethodThatUsesObject: 不能更改从调用方法传入的error 的本地值。这里有很好的解释stackoverflow.com/questions/2067563/…
Objective-C 中的* 与 C 中的含义完全相同;在这些情况下,您通常会看到(或看不到):
// Method signatures:
// Here the asterisk (*) shows that you have a pointer to an NSString instance.
+ (NSString *)stringWithString:(NSString *)aString;
// Method signatures, part two:
// Here the double asterisk (**) signifies that you should pass in a pointer
// to an area of memory (NSError *) where outError can be written.
- (BOOL)writeToURL:(NSURL *) atomically:(BOOL) error:(NSError **)outError;
// Method signatures make for good examples :)
// Here the asterisk is hidden; id is a typedef for void *; and it signifies that
// a pointer to some object of an indeterminate class will be returned
- (id)init;
// And a forth example to round it all out: C strings!
// Here the asterisk signifies, you guessed it, a pointer! This time, it's a
// pointer to the first in a series of const char; terminated by a \0, also known
// as a C string. You probably won't need to work with this a lot.
- (const char *)UTF8String;
// For a bit of clarity, inside example two, the outError is used as follows:
// Here the asterisk is used to dereference outError so you can get at and write
// to the memory it points to. You'd pass it in with:
// NSError *anError;
// [aString writeToURL:myURL atomically:YES error:&anError];
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atom error:(NSError **)outError {
// do some writing, and if it went awry:
if (outError != NULL)
*outError = [NSError errorWithName:@"NSExampleErrorName"];
return NO;
}
【讨论】: