目标C为什么我的NSMutableArray中的对象消失了?

时间:2013-06-17 19:08:43

标签: ios objective-c nsmutablearray

我是Objective-C和iOS的新手。我遇到了一些可能很容易纠正的问题,但我不知道为什么会发生这种情况。

我会尝试简要介绍一下我正在做的事情,并希望它有足够的信息来发现错误。

PolygonView.h是一个UIView类型的类,它像这样声明NSmutablearray:

@property(nonatomic, retain) NSMutableArray *polys;

我在PolygonView.m的initWithFrame:(CGRect)Frame方法中初始化它,如下所示:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    polys = [[NSMutableArray alloc]init];
    [self loadCsv];
    return self;
}

在loadCSV中我加载一个csv用它来创建一些多边形对象并做一些其他的东西,但这里是它的要点:

poly* p;
p = [[poly alloc] init];
// here I set a few properties on p from the csv file and then add p to polys like this:
[polys addObject:p];

在方法结束时,我使用nslog打印计数,如下所示:

NSLog(@"polys size = %i", [polys count]);

这会在控制台上打印“polys size = 100”。

然后我决定做自己的drawRect。并且它的开头使用相同的nslog来打印大小/计数,但控制台上会打印“polys size = 0”。

我做错了什么?如何从drawRect方法访问我添加到此数组的对象?

编辑: 这是完整的polygonView.h文件:

#import <UIKit/UIKit.h>

@interface PolygonView : UIView{
        NSMutableArray *polys;
}

@property(nonatomic, retain) NSMutableArray *polys;

-(void)loadCSV;

@end

编辑2:完整的多边形

//
//  PolygonView.m
//  Polygon2
//

#import "PolygonView.h"
#import "poly.h"


@implementation PolygonView
@synthesize polys;

-(id)init
{
    NSLog(@"regular init");

    self = [super init];
   if (self) {
        self.polys = [[NSMutableArray alloc]init];
        [self loadCsv];

    }
    return self;
}
- (id)initWithFrame:(CGRect)frame
{
    NSLog(@"init with frame");
    self = [super initWithFrame:frame];
    if (self) {
        self.polys = [[NSMutableArray alloc]init];
        [self loadCsv];

    }
    return self;
}

-(void)loadCsv
{
    poly* p;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"DivisoesEstaduais" ofType:@"csv"];
    NSString *testString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSString *newString = [testString stringByReplacingOccurrencesOfString:@"," withString:@"."];
    if (newString) {
        NSMutableArray *arrr = [newString componentsSeparatedByString:@"\n"];
        for (int i = 0; i < [arrr count]; i++){
            if ([[arrr objectAtIndex:i] length] > 0){
                p = [[poly alloc] init];
                NSMutableArray *arrayatual = [[arrr objectAtIndex:i] componentsSeparatedByString:@";"];
                [p setPolyid:[arrayatual objectAtIndex:0]];
                [p setPartid:[arrayatual objectAtIndex:1]];
                [p setPointid:[arrayatual objectAtIndex:2]];
                [p setx:[arrayatual objectAtIndex:3]];
                [p sety:[arrayatual objectAtIndex:4]];
                [self.polys addObject:p];
                NSLog(@"polys size = %i", [self.polys count]); // this increases from 1 to 100
            }  
        }
        NSLog(@"polys size = %i", [self.polys count]); // this prints 100
    }else{
        NSLog(@"not");
    }
}

- (void)drawRect:(CGRect)rect{
    srandom( time( NULL ) );
    CGContextRef context= UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, random() % 250, random() % 250, random() % 250, 1.0);
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    CGContextFillPath(context);
    int oldtemp = 0;
    NSLog(@"drawRect polys pointer = %@", self.polys); // this is null
    NSLog(@"polys size = %i", [self.polys count]); // this is zero
    for (int i = 0; i < [polys count]; i++){
        poly *p = [polys objectAtIndex:i];
        int temp = p.getPolyid.intValue;
        if (temp == oldtemp){
            CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
            CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
            CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
            UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
            CGContextSetFillColorWithColor(context, color.CGColor);
            CGContextFillPath(context);
            NSLog(@"movetopoint");
            CGContextMoveToPoint(context, [p.getx floatValue]+160, [p.gety floatValue]+160);
            oldtemp++;
        }else{
            CGContextAddLineToPoint(context, [p.getx floatValue]+160, [p.gety floatValue]+160);
            NSLog(@"addlinetopoint");
        }
    }

    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
   UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillPath(context);
 }

@end

这里是viewController.m:

//
//  ViewController.m
//  Polygon2
//
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
     self.view.multipleTouchEnabled = YES;
    PolygonView * pv = [[PolygonView alloc] init];
    [self.view addSubview:pv];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

EDIT3:

George Sachin的解决方案有效:使用viewDidAppear而不是viewDidLoad。但是为什么viewDidLoad会给我带来麻烦?这是拉链项目,以防有人想看一看并试图找出答案。 http://www.mediafire.com/download/b9ueqkqbmxswd7a/Polygon2_3.zip

对我来说,ViewDidload是我应该使用的。我应该从不使用它吗?

2 个答案:

答案 0 :(得分:2)

最终修改:

当您为UIView创建初始化程序时,您应该始终调用super的initWithFrame:或initWithCoder:当您使用.xib时

将您的代码更改为:

-(id)init
{
NSLog(@"regular init");

self = [super initWithFrame:CGRectMake(0, 0, 20, 20)]; // Replace with the dimensions you want
if (self) {
    self.polys = [[NSMutableArray alloc]init];
    [self loadCsv];

}
NSLog(@"(init)polys size = %i", [self.polys count]); 

return self;
}

答案 1 :(得分:0)

尝试这样做:

1)当您将@property(nonatomic, retain) myObj设置为对象时,您应该在.m文件中@synthesize myObj

2)因为HSNN说您应该通过self.myObj

访问它

3)最好在这部分之间进行初始化

if (self) {
    // Initialization code
}

短语“初始化代码”不是偶然放在那里))

问题的根源很可能被遗忘@synthesize,但最好覆盖所有3个步骤。

祝你好运。随便问一下这是否会有所帮助)