views:

57

answers:

3

I am getting confused with how to handle Integers in Objective C.

If I define the following:

NSInteger i = 6;
NSLog(@"%d", i);

I expect it to print 6 to the console.

however I have an NSInteger within an object which is obviously reference by a pointer so I get very difference results.

For example:

@interface Section : NSObject {
NSInteger Id;
}

@property (nonatomic, assign) NSInteger Id;

Please assume this has been synthesized in the implementation.

I create the object set its value and access it again as follows:

Section *section = [[Section alloc] init];
section.Id = 6;

NSMutableArray *sections = [[NSMutableArray alloc] init];
[sections addobject:section];

Section *sectionB = [setions objectAtIndex:0];
NSLog(@"%d",  sectionB.Id);

This has the strange effect of printing the memory address ie a number like 5447889. Why can I not just get the value?

I have tried using:

NSInteger sid = [[section Id]integerValue];

But I then get the warning Invalid receiver type 'NSInteger' and sometime get an error Program received signal: “EXC_BAD_ACCESS”.

I would really like to know how to handle Integers, or any values for that matter properly.

Many Thanks

A: 

It looks like you're accessing uninitialized memory; 5447889 doesn't look like a pointer value—pointers are usually word-aligned, and 5447889 isn't word aligned.

Maybe you could cut and paste your actual code. This has typos such as addobject instead of addObject and setions instead of sections.

Does it work if you keep things simple and do NSLog(@"%d", section.Id) to skip messing with the array?

Dominic Cooney
I am unable to post the full code at this time because im away from my mac. I don't know of it helps but im my production code the value of section.Id is being set from data parsed from json. Could it be a casting issue? Regarding the number I posted 5447889, this was just some random example numbers.
Chris
You should confirm the value that you're *setting* `Id` to.
Dominic Cooney
A: 

Regarding the strange values, see Dominic Cooney's answer.

Regarding the EXC_BAD_ACCESS: [[section Id]integerValue]; doesn't work because it then tries to interpret the NSInteger as an object and tries to send the message integerValue to it, which can't work. It's an integral number, not an object.

DarkDust
+1. Great explanation.
Dominic Cooney
A: 

Think I found the answer to my own question. Setting the value of an NSInteger to a value of say 6 is fine. The problem I have is I am setting it to the value returned from a Json string using the following:

NSInteger i = [jsonResult objectForKey:@"Id"];

which should be:

NSInteger i = [[jsonResult objectForKey:@"Id"] integerValue];

I have not tested this but makes sense based on what DarkDust said about integerValue taking an object and not an Integer.

Thanks for your input.

Chris