How to pass ivar into a function and set it without losing the reference to the original object

StackOverflow https://stackoverflow.com/questions/15162328

  •  16-03-2022
  •  | 
  •  

سؤال

I am passing an ivar (NSMutableArray) into some method. I was expecting that if I modify the object inside the function, it would be reflected outside the function, but in this case I need to set the object; something like the following:

- (void) someMethod:(SMResponseObject *)response onData:(NSMutableArray *)imAnIvar {
    imAnIvar = [response objects];
    //Some other stuff
}

But I noticed that the memory reference of imAnIvar inside the function changes when I set it, and given that, the actual ivar doesn't change. I understand that the problem is that I'm changing the reference of the object inside the method, so it stops pointing to the ivar and then it points to some other random memory direction.

I thought about one solution to this problem, and it can be to ensure that the ivar is not nil before calling the function and do something like this:

- (void) someMethod:(SMResponseObject *)response onData:(NSMutableArray *)imAnIvar {

    NSMutableArray *data = [response objects];
    [arrayForTableView removeAllObjects];
    for(id element in data){
        [imAnIvar addObject:element];
    }
    //Some other stuff
}

So I use the original object instead of setting it directly. The problem is that in order for this to work I need to ensure that the ivar is not nil, which I think is not clean, because I'll need to do something like this on every call to the method:

if(!_ivar){
  //alloc it
}

So my question is: Is there a way to force the local scope variable to point to the original variable even if I'm setting it? if not, is there any cleaner way to make this work?

هل كانت مفيدة؟

المحلول

Do you mean this?

- (void)setFoo:(SomeClass **)objPtr
{
    *objPtr = someOtherObject;
}

// call it as:

SomeClass *foo = someObject;
NSLog(@"Before: %@", foo);
[self setFoo:&foo];
NSLog(@"After: %@", foo);

نصائح أخرى

Why not use a getter for the array so that you need not check for the array being nil while using it?

-(NSMutableArray *)iAmAnIvar {
   if(_iAmAnIvar == nil) {
     _iAmAnIvar = [NSMutableArray array];
   }
   return _iAmAnIvar;
 }

And when you have to set a value to the array, as you mentioned in your question, you could use

[self.iAmAnIvar removeAllObjects];
[self.iAmAnIvar addObject:someObj];

I believe you can use the - (id)copy; function of NSObject

so your code might look like this:

 - (void)someFunction:(NSString *)someArg
 {
     NSString *str = [someArg copy];
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top