ios - Objective C 为什么我的 NSMutableArray 中的对象消失了?

标签 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

编辑3:

George Sachin 的解决方案奏效了:使用 viewDidAppear 而不是 viewDidLoad。但为什么 viewDidLoad 给我带来了麻烦?这是压缩的项目,以防有人想看一看并尝试弄清楚。 http://www.mediafire.com/download/b9ueqkqbmxswd7a/Polygon2_3.zip

在我看来 ViewDidload 是我应该使用的那个。我不应该使用它吗?

最佳答案

最终编辑:

当您为 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;
}

关于ios - Objective C 为什么我的 NSMutableArray 中的对象消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17154952/

相关文章:

objective-c - 递归-flattenMap : with Reactive Cocoa + OctoKit (fetching dynamic object graph from web service)

objective-c - iOS - 视频不播放

ios - 检查 NSArray 是否排序

iphone - 为什么我的对象没有被添加到数组中?

ios - Autolayout 动画约束不动画 subview

ios - 存储在 'parameter name' 中的值永远不会在注释宏中读取

ios - 将带有JSON的NSString转换为NSDictionary

iphone - 在表格 View 中插入图像?

ios - 被 NSMutableArray sortUsingDescriptors : exception 搞糊涂了

ios - View 模型可以监听其自身属性的变化吗?