views:

208

answers:

3

Hello everyone,

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

+1  A: 

I don't see any problem doing this.

However there is a problem with your code - not technically, but conventionally.

You shouldn't be prefixing your own custom objects with NS - That's Apple's Foundation framework prefix.

You should prefix your own classes with an abbreviation of your name, or the app's name or your company name, etc.

Apple use many prefixes for their frameworks and if you use the same prefixes you'll eventually run into a clash between class names.

Jasarien
+1  A: 

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 myFunction in the code above isn't defined as a function but rather the instance method of a class. It won't work standalone like this:

myFunction(temObj);

... instead you have to call it like:

[someInstanceOfAClass myFunction:tempObj];

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:

-(void)myFunction:(NSMyObject*) obj;
{
    [obj setI:0];
    NSLog(@"obj.i = %d",obj.i);
}

... and see the value of obj.i you just set printed to the console.

If you do call it properly but the value of obj.i still 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.

TechZen
A: 

I dont see any syntax issue in your code, but you can follow the recommended practices like, you can make the property for your variable as:

@property(nonatomic, readwrite) NSInteger i;

And than in implementation class do synthesize it as

@synthesize i;

Now when you going to set the value in your method your code should do the job :

-(void)myFunction:(NSMyObject*) obj;
{
    [obj setI:0];
}

One more thing, try to use some standard and recommended coding conventions, sometime names are keywords and they cause problem even they dont give any error or warning at compile time.

Ansari