iOS Objective-C:NSMutableArray返回垃圾

时间:2012-12-02 20:05:41

标签: objective-c ios nsmutablearray

我正在尝试使用C风格的矢量并将其转换为NSMutable数组对象。

这是功能:

+(NSMutableArray*)arrayFromPoints:(vector<Point2f>&)points
{
    NSMutableArray* pointArray = [[NSMutableArray alloc] init];
    for (int i=0;i<points.size();i++)
    {
        Point2f point = points[i];
        JBPoint* point2 = [[JBPoint alloc]initWithX:point.x andY:point.y];
        [pointArray addObject:point2];
    }
    return pointArray;
}

自定义点类:

 @implementation JBPoint

float _x;
float _y;

-(id) initWithX:(float)x andY:(float)y
{
    if (self=[super init])
    {
       _x = x;
       _y=y;
    }
    return self;
}

-(float)x{ return _x;}
-(float)y {return _y;}

@end

测试输出:

for (JBPoint* pnt in array)
{
    NSLog(@"%f, %f", pnt.x, pnt.y);
}

我除了它输出数组,但每次它只给我最后一个值!有谁知道为什么?

我认为他们可能指向同一个对象,但他们有不同的内存地址。

2 个答案:

答案 0 :(得分:0)

所以我想出了问题所在。 float _x; float _y;被视为类变量而不是实例变量。将班级更改为:

@interface JBPoint()
{
    float _x;
    float _y;
}

@end

@implementation JBPoint

-(id) initWithX:(float)x andY:(float)y
{
    if (self=[super init])
    {
       _x = x;
       _y=y;
    }
    return self;
}

-(float)x{ return _x;}
-(float)y {return _y;}

@end

答案 1 :(得分:0)

如果你写了

@property (nonatomic, readonly) float x;
@property (nonatomic, readonly) float y;

在你的头文件中你不需要声明实例变量(并且本来可以避免这个问题)你可以删除你写的getter方法,因为这些方法都是由编译器为你和你的自定义init生成的方法将继续工作(使用最新的编译器)。

这样做是个好主意,因为:

  • 少代码
  • 您的意图很明确 - 2个客户只读的变量
  • 遵循语言约定

如果您使用的是较旧的编译器(较旧版本的Xcode),那么您还需要@synthesize这样的访问器:

@synthesize x = _x;

一些有趣的旁白:

使用最新的编译器,您不需要类扩展。

@implementation{
    float _x;
    float _y;
}

也会奏效。

正如WWDC 2012会话视频413中所引用的,当前推荐的编写init方法的模式是:

...
self = [super init];
if (self) {
...
}
return self;
相关问题