开发者

Objective-c symbols ** & +-

Just when I think I'm getting comfortable with Objective-c the mentioned symbols totally throw me down a rabbit hole...

**     a double pointer??

&     what sort of things can I do with &reference, is a @property? a full on object? weird pointer razzledazzle?

±     I see both a + or a - before method declarations; I've seen Java annotate some datatype declarations by manually typing the + and the magic of compiling in Eclipse would change them to a -

I'm likely asking repetitious questions and/or way outta the ballpark on my guesses; thanks fo开发者_JS百科r answers/edits.


You're getting into the C portion that objective-c is built on top of.

** is a pointer to a pointer. Since functions in C take arguments by value, it means you can't change the value of the argument in that function. But, by providing a level of indirection and passing a pointer to the pointer, you can change the value.

& means it's a reference. If an argument takes a ** and you have a * variable, pass a reference to it.

Foo *foo;
[self changeFoo: &foo];

- (BOOL)changeFoo: (Foo **)foo
{
     // dereference the double pointer and assign a val = alloc init returns a *
     *foo = [[Foo alloc] init];
     return YES;
}

A common usage in objective-c / cocoa is NSError. It's essentially an out argument.

NSError *err;
BOOL success = [self doSomething:@"Foo" error:&err];

- (BOOL)doSomething:(NSString*)withData error:(NSError**)error
{
}


As you might know, a pointer points to the address of an object and is the way you reference an object. A double pointer is sometimes used in Objective-C, mainly for returning NSErrors, where you want to get back the address, i.e. a pointer, to an error object (NSError) if an error occurred, thus you pass in a pointer assigned to null and the caller can change that pointer so that it points to the address of another pointer which in turn points to an NSError object.

The ampersand (&) is mostly used by the lower level C APIs, e.g. Core Graphics. They are used to reference things, like the current context. As long as most of your code uses square brackets around its method calls you won't see these very often.

Using a + or a - before a method declarations is used to differentiate between class (+) and instance (-) methods. A class methods is called on the class itself (such as alloc), while a instance method is called on an instance of that object (such as init).


- and + before a method declaration designate an instance method and a static class method. To use an instance method you have to create an object of your class before you can call its method, a static method can be called directly from a class type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜