开发者

Objective-C handling integer values

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


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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜