Search code examples
objective-cpointersnsarraydereference

Change the values within NSArray by dereferencing?


I've come across a problem related to pointers within arrays in objective-c.

What I'm trying to do is take the pointers within an NSArray, pass them to a method, and then assign the returned value back to the original pointer(the pointer which belongs to the array).

Based on what I know from C and C++, by dereferencing the pointers within the array, I should be able to change the values they point to... Here is the code I'm using, but it is not working (the value phone points to never changes based on the NSLog output).

NSArray *phoneNumbers = [phoneEmailDict objectForKey:@"phone"];
    for (NSString* phone in phoneNumbers) {
        (*phone) = (*[self removeNonNumbers:phone]);
        NSLog(@"phone:%@", phone);
    }

And here is the method signature I am passing the NSString* to:

- (NSString*) removeNonNumbers: (NSString*) string;

As you can see, I am iterating through each NSString* within phoneNumbers with the variable phone. I pass the phone to removeNonNumbers:, which returns the modified NSString*. I Then dereference the pointer returned from removeNonNumber and assign the value to phone.

As you can tell, I probably do not understand Objective-C objects that well. I'm pretty sure this would work in C++ or C, but I can't see why it doesn't work here! Thanks in advance for your help!


Solution

  • Yeah, that's not going to work. You'll need an NSMutableArray:

    NSMutableArray * phoneNumbers = [[phoneEmailDict objectForKey:@"phone"] mutableCopy];
    for (NSUInteger i = 0; i < [phoneNumber count]; ++i) {
      NSString * phone = [phoneNumbers objectAtIndex:i];
      phone = [self removeNonNumbers:phone];
      [phoneNumbers replaceObjectAtIndex:i withObject:phone];
    }
    [phoneEmailDict setObject:phoneNumbers forKey:@"phone"];
    [phoneNumbers release];