开发者

iOS/Objective-C: NSInteger gets lost during simply Coordinates2D object creation

I'm tearing my hair out over this.. I've no idea what's going wrong.

I've created a very simple Coordinates2D class to store two NSInteger values, as well as a string representation for use with NSLog. I'm running this code in the iOS 4.3 iPad simulator bundled with the latest version of xCode.

For some reason the integer values passed to the initX:Y: constructor gets lost. The code below provides Coordinates2D and some code to print an arbitrary float value in its original form, cast as an int, cast as an NSInteger, and then inside the Coordinates2D object.

You should see, as I do, that the value gets lost inside the Coordinates2D constructor; the 'coords.x' argument in NSLog is printed as a random, large integer indicating its value has been lost in memory.

Can anyone help me see why this happens? I can't see what I'm doing wrong.

Many thanks!

Coordinates2D.h

#import <Foundation/Foundation.h>
@interface Coordinates2D : NSObject {
    NSInteger x,y;
    NSString *asString;
}
@property (nonatomic) NSInteger x,y;
@property (nonatomic, retain) NSString *asString;
-(void)updateStringRepresentation;
-(id)initX:(NSInteger)x Y:(NSInteger)y;
@end

Coordinates2D.m

#import "Coordinates2D.h"
@implementation Coordinates2D
@synthesize x,y,asString;

-(id)initX:(NSInteger)x_ Y:(NSInteger)y_ {
    NSLog(@"coords: %i, %i",x_,y_);
    if ((self = [super init])) {
        self.x = x_;
        self.y = y_;
        NSLog(@"Coordinates stored %i as %i",x_,self.x);
        [self updateStringRepresentation];
    }
    return self;
}
/*
-(void)setX:(NSInteger)newX {
    x = newX;
    [self updateStringRepresentation];
}

-(void)setY:(NSInteger)newY {
    y = newY;
    [self updateStringRepresentation];
}
*/
-(void)updateStringRepresentation {
    self.asString = [NSString stringWithFormat:@"%i,%i",x,y];
}

-(void)dealloc {
    [asString release];
    [super dealloc];
}
@end

Example of problem:

Coordinates2D *coords 开发者_如何学Python= [[Coordinates2D alloc] initX:(NSInteger)(202.566223/200.00) Y:0.0f];
NSLog(@"202.566223/200.00 = %f, as int:%i, as NSInteger:%i, as Coordinates2D:%i",
      202.566223/200.00, (int)(202.566223/200.00), (NSInteger)(202.566223/200.00), coords.x);


I read awhile ago that you should never use the property accessor in init methods.


I think you want to change:

@property (nonatomic) NSInteger x,y;

to:

@property (nonatomic, assign) NSInteger x,y;

That should fix the error, as it runs fine when I put it in an xcode project.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜