I cannot change the value of an instance variable inside a function.
I have defined a class:
// info.h
#import <Foundation/Foundation.h>
@interface NSMyObject : NSObject
{
NSInteger i;
}
-(void) setI:(NSInteger)v;
@end
#import "info.h"
@implementation NSMyObject
-(void) setI:(NSInteger)v ;
{
i=v;
}
- (void)dealloc {
[super dealloc];
}
@end
I call a function ‘myFunction’ with parameter temObj which is a NSMyObject instance.
myFunction(temObj);//temObj is NSMyObject
In the function, I can change the value of the instance variable of parameter obj.
-(void)myFunction:(NSMyObject*) obj;
{
[obj setI:0];
}
… expecting this to change the content of temObj.
But when I check the results of operation on obj in function myFunction the value of temObj.i has not changed.
Welcome any comment
Thanks
You should be able to change the value of an attribute of a passed object inside a function or method.
I think your problem is that
myFunctionin the code above isn’t defined as a function but rather the instance method of a class. It won’t work standalone like this:… instead you have to call it like:
I think that is where your problem is. You should be getting a compiler warning if you try to call a method like a function.
If you call the method properly, you should be able to do this:
… and see the value of
obj.iyou just set printed to the console.If you do call it properly but the value of
obj.istill doesn’t change, the most likely explanation is that your looking at different instance of NSMyObject and not the one you passed to the method.