Stephen Silber
Stephen Silber

Reputation: 283

How do you access a pointer to a pointer for an id object?

I am dabbling in jailbreak development/tweaks and I already know that this goes against Apple's SDK rights, etc. I am fairly new to objective-c and am unsure how to access a pointer to a pointer to a value. Here is the header function:

- (id)_newCKSMSMessage:(id *)arg1;

I have tried several attempts to get access to the value of arg1:

id msg = &arg1;
id *msg = &arg1;

How do I access the value being pointer to by arg1?

Upvotes: 2

Views: 246

Answers (4)

Bill Dudney
Bill Dudney

Reputation: 3358

Before you dereference a pointer you have to make sure to check if it's NULL;

if(NULL != arg1) {
    id msg = *arg1;
    NSLog(@"msg = %@, [msg class] = %@", msg, NSStringFromClass([msg class]));
}

When you pass an object to _newCKSMSMessage:(id*)arg1 you do that like this;

id gak = [[Gak alloc] initWithInterestingStuff:interestingStuff];
[something _newCKSMSMessage:&gak];

It is improper for you to have methods that begin with '_'. You are likely to conflict with Apple's private methods if you do that.

Upvotes: 1

Chuck
Chuck

Reputation: 237010

I think you have another problem that you don't know you have.

The argument to this method is most likely not a valid object. When you see a pointer to a pointer to an object, that is almost always a "return by reference" parameter. The caller passes in the address of some variable, and the method is supposed to set the variable to some object. For example:

- (void)tellMeHello:(id *)message {
    if (message) {
        *message = @"Hello!";
    }
}

// It's used like this:

id thisWillBeTheMessage; // it's nothing right now
[someObject tellMeHello:&thisWillBeTheMessage];
NSLog(@"%@", thisWillBeTheMessage); // prints "HELLO!"

I'm not familiar with the method in question here, but there's pretty much no other reason to pass a pointer to a pointer to an Objective-C object AFAIK.

EDIT: OK, I just thought of another reason: If you're passing a C array of objects. But that's much less common. It's pretty much only done in a couple of NSArray initializers. It's more the exception than the rule.

Upvotes: 2

Sailesh
Sailesh

Reputation: 26197

Isn't & a address of operator?

So id msg = &arg1 would mean pointer to arg1 (third level!)

You should do id msg = *arg1

Upvotes: 0

BlackJack
BlackJack

Reputation: 2876

This is fundamental to C. Here's an example:

int val = 5;
int* valPtr = &val;        //valPtr points to val;
int** valPtrPtr = &valPtr; //valPtrPtr is a pointer to a pointer to val
int newVal = **valPtrPtr;  //newVal = 5

Let's say you have a pointer to a pointer called vPtr. Whenever you want to de-reference vPtr, you use (**vPtr) or *vPtr[k] for some k or vPtr[j][k] for some j,k. If accessing the value with array notation, be sure to have correct bounds or else you get undefined behavior.

Upvotes: 1

Related Questions