Reputation: 8493
I know there are differences between C/C++ and Objective-C, but what is the case when it comes to the pointer-mark *
? Is this not used for pointers in Objective-C, or are all objects pointers in this language?
I.E, if I try NSString string = @"Hello";
, XCode tells me to use NSString *string
instead. Does this still mean it is a pointer?
Let's say I have this standard method(as in, this is the way most methods look):
-(void)method:(NSString*)s;
then I would send something like this:
NSString *string = @"Hello";
[self method:string];
Would I save data time or allocation or access or whatever by doing everything like this:
-(void)method:(NSString**)s;
//and use it like this:
NSString *string = @"Hello";
[self method:&string];
Or is it a waste? If they are already pointers, I would guess they would be pointing to pointers this way.
?
Upvotes: 2
Views: 1517
Reputation: 119031
Objects themselves aren't pointers, they're areas of memory with data in them. The variables you're talking about are pointers to those objects:
NSString *string = @"Hello";
Here, 'string' is a pointer to anNSString
literal object. When passing this as a variable you're passing a reference to the object. The contents of the object (if it's a mutable object, which NSString
isn't) can be edited, but the reference can't.
By using NSString **
you're adding an extra level of indirection. Now you're passing a pointer to a pointer. The only reason you want to do that is when you want to allow the object (if there is one) to be edited as well as the reference to the object. For example, when calling a method that optionally returns an error:
NSError *error = nil;
[someone doStuff:(NSString *)string error:(NSError **)error];
Now someone can instantiate an NSError
and return it to you.
You should not use pointers to pointers unless this is your intention.
Upvotes: 8