将另一个类中的Item添加到另一个类的属性中。 Objective-C的

时间:2013-10-22 07:27:22

标签: ios objective-c xcode methods properties

所以我有两节课。按下保存按钮后,它会将self.screen.text addItem方法的值向下传递到第2类中的totalArray。如果我在{{1}中尝试NSLog @implementation方法,然后它将给出正确的输出,但如果我在addItem中执行,则输出为空。如何永久保存从class1传递到class2的属性的值?谢谢。 UITableViewController

的子类中的class2

Class 1 @interface

viewDidLoad

Class1 @implementation

//class1.h
#import class2.h
@interface class1 : superclass {

}

- (IBAction)buttonSave:(id)sender;

和class2 @interface

//class1.m
@interface class1 ()

@end

@implementation class1 {

}

- (IBAction)buttonSave:(id)sender {
  class2 *Obj = [[class2 alloc] init];
  [Obj addItem:self.screen.text];
}

class2 @implementation

//class2.h
#import class2.h
@interface {

}

@property (strong, nonatomic) NSMutableArray *totalArray;

4 个答案:

答案 0 :(得分:0)

尝试使用这样......

- (IBAction)buttonSave:(id)sender 
    {
      class2 *Obj = [[class2 alloc] init];

      Obj.totalArray = [[NSMutableArray alloc] init]; //alloc & init
      [Obj.totalArray addObject:self.screen.text];
      NSLog(@"screen.text %@", self.screen.text); // -- check here it may be null---- 
      NSLog(@"Obj.totalArray %@", Obj.totalArray);

    }

    @interface class2 ()

    @end

    @implementation {

    }

    - (void)viewDidLoad
     {
      [super viewDidLoad];

      NSLog(@"%@", self.totalArray); //But in here the output is null. ???

    }

答案 1 :(得分:0)

viewDidLoad之后调用

init,因此您的数组是nil。更改您的class2 init方法以接受该项目。

// In class2
-(id) initWithStyle:(UITableViewStyle)style andItem:(id)item {
    self = [super initWithStyle:style];
    if(self) {
        self.totalArray = [[NSMutableArray alloc] init];
        [self.totalArray addObject:item];
    }
    return self;
}

您的addItem将如下所示,

- (void) addItem:(id)item {
  //Just add, do not initialize again
  [self.totalArray addObject:item];
}

class1中的按钮操作现在看起来像

- (IBAction)buttonSave:(id)sender {
    class2 *Obj = [[class2 alloc] initWithItem:self.screen.text];
    //OR
    //class2 *Obj = [[class2 alloc] initWithItem:UITableViewStylePlain andItem:self.screen.text];
}

希望有所帮助!

答案 2 :(得分:0)

我认为您的问题是您使用了不同的class2对象。您在buttonSave中初始化的那个不是您正在显示的那个

在class1.h中添加一个属性

@property (nonatomic, strong) NSMutableArray *savedArray;

并修改buttonSave:

- (IBAction)buttonSave:(id)sender {
      self.savedArray = [[NSMutableArray alloc] init];
      [self.savedArray addObject:self.screen.text];
} 

您正在使用故事板,请尝试在class1.h中添加此内容,并在故事板中为此segue添加标识符class2Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"class2Segue"]) 
    {
        Class2 *tableController = (Class2 *)[segue destinationViewController];
        tableController.totalArray = self.savedArray;
    }
}

答案 3 :(得分:0)

您无法确保viewDidLoad方法何时调用...所以最好将值传递给init方法并设置initWithText:(NSString*)text{}。其他方面尝试在viewWillAppearviewDidAppear中调用NSLog仅用于测试目的。在iOS 7中,现在视图控制器的显示有点改变了。

相关问题