Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

seepel

macrumors 6502
Original poster
Dec 22, 2009
471
1
I'm a bit new to Cocoa programming and I understand how @synthesize will work with C type variables, like ints and floats. If I try to use it with something like an NSNumber, however, I don't understand what it's doing. Can anyone shed some light on the issue?
 
Thanks for the reference I'd been looking for a page like that. But I still don't quite understand, this is my conception.

If I use assign I would expect something like this
Code:
@property NSNumber *number

- (void)setNumber:(NSNumber*) n { number = n; }

and retain
Code:
@property (retain) NSNumber *number;

- (void)setNumber:(NSNumber*) n {
    [number release];
    number = n;
    [number retain];
}

and copy
Code:
@property (copy) NSNumber * number;

- (void)setNumber:(NSNumber*) n {
   number = [n copy];
}

At least with retain this isn't what I see. The number never seems to get set. So if I run this I get 0 back.

The class.
Code:
@interface SomeClass : NSObject {
    NSNumber *number;
};

@property (retain) NSNumber *number;
@end

@implementation SomeClass
@synthesize number;
@end

And the calling
Code:
[someClass setNumber:[NSNumber numberWithInt:5]];
NSLog(@"SomeClass number: %d",[[someClass number] intValue]);

The output
Code:
2010-04-02 12:42:09.260 SomeClass App[8842:207] SomeClass number: 0
 
Have you initialized the object someClass correctly?

And, imported the class .h where you want to use it?

Using exactly the class you posted here, I created a command line tool with the following main file:

Code:
#import <Foundation/Foundation.h>
#import "SomeClass.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    SomeClass *myObject = [[SomeClass alloc] init];
	
	[myObject setNumber:[NSNumber numberWithInt:5]];
	
	NSLog(@"SomeClass number: %d", [[myObject number] intValue]);
	
	// or
	
	NSLog(@"SomeClass number by dot notation: %d", [myObject.number intValue]);
	
	[myObject release];
	
    [pool drain];
    return 0;
}

Which worked perfectly, printing:

2
Code:
010-04-03 10:44:48.877 number[1277:a0f] SomeClass number: 5
2010-04-03 10:44:48.880 number[1277:a0f] SomeClass number by dot notation: 5

Hope this helps to identify where is the bug!
 
Have you initialized the object someClass correctly?

And, imported the class .h where you want to use it?

Using exactly the class you posted here, I created a command line tool with the following main file:
...
Hope this helps to identify where is the bug!

I must have had some other messy code somewhere that was interferring. I scrapped everything and started over and you're right, it does work as expected. Thank you.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.