0

I have a custom class with primitive data types as properties. If I create a instance of this class in a static method of another class, the primitive variables are somehow not changeable.

header

@interface CustomClass : NSObject {
double value;
}

@property (nonatomic) double value;

m file

@implementation CustomClass

-(id)init
{
    if ((self = [super init]))
    {
        self.value = 0;
    }
return self;
}

Create and return a instance of this class in a static method:

+(CustomClass *)CalculateValue:(double)val{
     CustomClass *customClass = [[CustomClass alloc] init];
     customClass.value = val;

     //The value is not changing after set!!
     return [customClass autorelease];
}

If i use an object instead of the primitive variable (eg. NSNumber) this problem does not occur.

mac
  • 42,153
  • 26
  • 121
  • 131
  • 1
    I see nothing wrong with your code. Show us where you are trying to read the value or exactly what makes you think the value is "not changing". – Firoze Lafeer Nov 29 '11 at 20:52
  • You seem to be missing a `@synthesize` line in your .m file. This should be throwing an error at compile-time. – Lily Ballard Nov 29 '11 at 20:55
  • I assume you synthesized the property. (or else the init would have crashed) – Firoze Lafeer Nov 29 '11 at 20:56
  • What exactly do you mean by the value is not changeable? – Lily Ballard Nov 29 '11 at 20:56
  • 1
    What you are doing is actually creating a "Class Method" not a "Static Method." You can read the differences between the two here: http://stackoverflow.com/questions/8089186/objective-c-difference-between-class-method-and-static-method. Also, is it possible to see how this class method is used in some code? – 5StringRyan Nov 29 '11 at 20:59
  • 1
    you do not need to declare the ivar 'double value;' if you have it as a property, not since Objective-C 2.0, it automatically handles that. – AndersK Nov 29 '11 at 21:00
  • You are right, its not need to declare the ivar, thanks. I found the problem, there is property in the class (the code here was just a sample code) with a retain count of 0 in viewDidLoad. How is this possible (should I ask a new question?) – user1072138 Nov 29 '11 at 21:33
  • @user1072138: There's only one object that will report a retain count of 0, and that's nil. Your property is nil. – Chuck Nov 29 '11 at 22:39
  • Does changing `@property (nonatomic) double value;` to `@property (nonatomic, assign) double value;` make a difference? – Ian Nov 30 '11 at 18:37

0 Answers0