从iPhone xcode中的另一个类访问数组

时间:2012-02-09 07:24:55

标签: iphone objective-c xcode

我在这个数组中得到了CGPoint值

@interface CanvasView : UIView{
 NSMutableArray *_array;
}
@property (nonatomic, retain) NSMutableArray *_array;

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint currentPoint = [touch locationInView:self];
    [_array addObject:[NSValue valueWithCGPoint: currentPoint]];
}

我已经在touchesEnded中调用了这个数组,它的工作正常我会得到nspoint的值

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
        NSLog(@"roomAtX:%@ ",_array);
    PieClass *myPieClass=[[PieClass alloc]initWithFrame:CGRectMake(8, 297, 200, 300)];
    [self addSubview:myPieClass];
}

这是我的控制台输出

"NSPoint: {595, 158}",
"NSPoint: {558, 154}",
"NSPoint: {535, 152}",
"NSPoint: {518, 152}",
"NSPoint: {500, 160}",
"NSPoint: {482, 175}",

现在我想将这个数组用于另一个类,以便我为另一个类调用它 像这样

- (void)drawRect:(CGRect)rect
{
      CanvasView *cnava =[[CanvasView alloc]init];
        NSLog(@"nextview:%@ ",cnava._array);

}

但是我得到nextview:(null) 请指导如何在其他类中访问该数组。

4 个答案:

答案 0 :(得分:1)

拥有PieClass

的属性
@interface PieClass : UIView{
    // ... other things.
}
@property (nonatomic, retain)NSMutableArray *pointsArray;

并且不要忘记合成它。现在,当您初始化PieClass时,也将该数组传递给此

PieClass *myPieClass=[[PieClass alloc]initWithFrame:CGRectMake(8, 297, 200, 300)];
myPieClass.pointsArray = _array;
[self addSubview:myPieClass];

现在在你的drawRect

- (void)drawRect:(CGRect)rect
{
      //CanvasView *cnava =[[CanvasView alloc]init]; you don't need to do this
      NSLog(@"nextview:%@ ",self.pointsArray);  //passed from previous class

}

答案 1 :(得分:0)

您必须使用旧对象CanvasView。因此,如果您分配并初始化一个新对象CanvasView,则_array将为null。您必须为_array分配内存并初始化它,或者您必须先将其设置为属性。

因此,对于要绘制的当前对象,您需要传递CanvasView对象的引用,以检测触摸并保存点。

我希望我足够清楚。

答案 2 :(得分:0)

将对象(此时,数组)保存到第一个类中的NSUserDefaults

  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        CGPoint currentPoint = [touch locationInView:self];
        [_array addObject:[NSValue valueWithCGPoint: currentPoint]];

        NSUserDefaults *myArray=[NSUserDefaults standartuserdefaults];
        [myArray setObject:_array forKey:@"keyToArray"];

    }



    - (void)drawRect:(CGRect)rect
    {  
           NSArray *yourArray=[[NSUserDefaults standartuserdefaults] objectForKey:@"keyToArray"];
          //CanvasView *cnava =[[CanvasView alloc]init];
            NSLog(@"nextview:%@ ",yourArray);

    }

试试这个

答案 3 :(得分:0)

如果我理解正确,你需要这个班级成为一个单身人士

首先在.h文件中创建一个类方法:

@interface CanvasView : UIView{
 NSMutableArray *_array;
}
...
+ (CanvasView *)sharedInstance;
...

然后在.m文件中:

@implementation CanvasView
...
static CanvasView *sharedHelper = nil;
...
+ (CanvasView *)sharedInstance
{
    @synchronized(self) 
    {
        if (!sharedHelper) 
        {
            sharedHelper = [CanvasView new;
        }
    }
    return sharedHelper;
}

并称之为:

CanvasView *view = [CanvasView sharedInstance];