将数组和字符串传递给自定义UIView类(子类)(iOS)

时间:2011-11-30 22:26:31

标签: ios uiview uiscrollview nsmutablearray subclass

希望你能提供帮助。

我创建了自己的Custom UIView,并且我正在尝试传入一个NSMutableArray,我已经从sqlite DB的数据中设置了它。我从ViewController获得了NSLog的数组,一切都正确显示。

但是我想将这个NSMutableArray传递给我的自定义UIView(它实际上是一个UIScrollView),这样我就可以做一些魔术。但是当我这样做时,我的NSLog显示输出为(null)。

这是我的代码(我还传递了一个测试字符串,以帮助查看它是否特定于Array,但事实并非如此):

viewcontroller.m(刚显示Custom类调用 - NSLog输出Array内容(参见示例结尾)

- (void)viewDidLoad
{
...
NSString *teststring = @"Testing";
NSLog(@"Subitems: %@", subitems);
SubItemView* subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)];
subitemview.cvSubitems = subitems;
subitemview.teststring = teststring;
[self.view addSubview:subitemview];
}

customview.h

#import <UIKit/UIKit.h>

@class SubItemView;

@interface SubItemView : UIScrollView {

}


@property (nonatomic, retain) NSMutableArray *cvSubitems;
@property (nonatomic, retain) NSString *teststring;

@end

customview.m

#import "SubItemView.h"

@implementation SubItemView

@synthesize cvSubitems;
@synthesize teststring;

- (id)initWithFrame:(CGRect)frame
{   
    CGRect rect = CGRectMake(0, 0, 400, 400);
    NSLog(@"Subclass Properties: %@", self.cvSubitems);
    self = [super initWithFrame:rect];

    if (self) {
        // Initialization code
    }
    return self;
}

viewcontroller.m中的第一个NSLog输出:

Subitems: (
    "<SubItems: 0x6894400>",
    "<SubItems: 0x6894560>"
)

Custom UIScrollView输出的第二个NSLog:

Subclass Properties: (null)

我是一个新手,所以我显然在这里遗漏了一些东西(可能很明显)。我真的很难将一个数组甚至一个简单的字符串传递给一个Custom类,只是通过NSLog输出它的内容。

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

当调用initWithFrame方法时,您的cvSubitems属性尚未设置,因为在调用initWithFrame之后只设置了

再次尝试在初始化视图后调用的方法中记录数组值,或者提供自定义init方法(例如initWithMyData: andFrame:)来解决此问题。

答案 1 :(得分:1)

因此,为了澄清已经说过的话,你要打乱了。

1| SubItemView* subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)];
2| subitemview.cvSubitems = subitems;
3| subitemview.teststring = teststring;
  • 在第1行,您正在initWithFrame:
  • 上调用SubItemView方法
  • 在第2和第3行,您正在设置ivars

关键是你在initWithFrame:方法返回后设置了ivars(第2 + 3行)。

但是您正试图在initWithFrame:方法中打印ivars

您还试图在分配self之前记录ivars,这不是一个好主意

NSLog(@"Subclass Properties: %@", self.cvSubitems);
self = [super initWithFrame:rect];

要证明它们已被设置,您可以从实例化的位置进行打印:

SubItemView *subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)];
subitemview.cvSubitems = subitems;
subitemview.teststring = teststring;
NSLog(@"Subclass Properties: %@", subitemview.cvSubitems);