2014-02-18 27 views
1

每次调用某个方法时,都需要创建一个对象的新实例。所以我需要创建一个循环来检查像newInstance1这样的变量计数器的存在,并且如果找到它,则创建newInstance2。你怎么能从一个nsstring创建一个类?目标是创建视图,以便可以在表示对象的网格上拖动。下面是创建新的对象,并查看使用NSString创建类的实例

//method creates view with new fixtureIcon 
- (IBAction)makeView:(id)sender { 


    rectString = [NSString stringWithFormat:@"0,120,%f,%f", pm.fixWidth, pm.fixHeight]; 
    _try = [[fixtureIcon alloc]init]; 

    _try.fixImg = pm.fixImage; 
    _try.name = pm.name; 
    [fixController addObject:_try];  




    _testBox = [[addObjectView alloc]initWithFrame:NSRectFromString(rectString)]; 



    NSImageView *iconView = [[NSImageView alloc]initWithFrame:NSMakeRect(0, 0, 75, 75)]; 
    testView1Controller = [[NSViewController alloc]init]; 
    testView1Controller.view = _testBox; 


    [_testBox setWantsLayer:YES]; 




    _testBox.layer.masksToBounds = YES; 
    _testBox.layer.cornerRadius = 2.0; 
    _testBox.layer.borderWidth = 2; 
    _testBox.layer.borderColor = [[NSColor darkGrayColor]CGColor]; 

    //this tells the window to add our subview testbox to it's contentview 

    [testView1Controller setView:_testBox]; 

    [testView1Controller bind:@"representedObject" toObject:fixController withKeyPath:@"content" options:nil]; 

    [mainWin addSubview:_testBox]; 
    NSTextField *obLabel = [[NSTextField alloc]initWithFrame:CGRectMake(0, 0, 50, 40)]; 
    [obLabel bind:@"value" toObject:testView1Controller withKeyPath:@"representedObject.type" options:nil]; 
    [obLabel setBackgroundColor:[NSColor clearColor]]; 
    [obLabel setSelectable:false]; 
    [obLabel setEditable:false]; 
    [obLabel setBackgroundColor:[NSColor grayColor]]; 
    [obLabel setBordered:false]; 
    [obLabel setTextColor:[NSColor whiteColor]]; 
    [iconView bind:@"value" toObject:testView1Controller withKeyPath:@"representedObject.fixImg" options:nil]; 
    //[_testBox addSubview:obLabel]; 
    [_testBox addSubview:iconView]; 

的原因,我需要新的实例是方法,所以我不覆盖的属性值和失去我的representedObject数据为每个视图。

+1

考虑使用NSMutableArray并对其做addObject。 – Anna

+0

@Anna我仍然需要改变实例的初始化名称。右? –

+0

如果你在你的问题中解释你正在尝试完成什么或者你正在试图解决什么问题,这可能会有所帮助。我的意思是:声明一个名为myInstances的NSMutableArray。创建并添加您的对象。然后你可以通过索引访问它们(例如'[myInstances objectAtIndex:2]')。 – Anna

回答

4
id object = [[NSClassFromString(@"NameofClass") alloc] init]; 
+0

创建类的实例本身不是类名。像someclass * stringforclassinstance = [someclass alloc] init]; –

+2

此代码创建一个类型为“NameofClass”的类的实例。另外,你问题的主题是:“用NSString创建类的实例”。这是这段代码所做的。如果您的意思不同,请重新提出或编辑您的问题。 – Aaron