ios - 将另一个类的项目添加到另一个类的属性。 Objective-C

标签 ios objective-c xcode methods properties

所以我有两个类。当按下保存按钮时,它将从 self.screen.text 传递值通过 addItem totalArray 的方法在第 2 类。如果我尝试 NSLog@implementationaddItem方法,然后它会给出正确的输出,但如果我在 viewDidLoad 中这样做,输出为空。如何永久保存从 class1 传递到 class2 属性的值?谢谢你。 UITableViewController 子类中的 class2

1 类@interface

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

}

- (IBAction)buttonSave:(id)sender;

Class1 @implementation
//class1.m
@interface class1 ()

@end

@implementation class1 {

}

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

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

}

@property (strong, nonatomic) NSMutableArray *totalArray;

类 2 @实现
@interface class2 ()

@end

@implementation {

}

- (void) addItem:(id)item {
  self.totalArray = [[NSMutableArray alloc] init]; //alloc & init
  [self.totalArray addObject:item]; //add object to the total array
  // NSLog(@"%@", self.totalArray); If I NSLog in within this method then everything works as expected.
}

- (void)viewDidLoad {
  [super viewDidLoad];

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

}

最佳答案

我认为您的问题是您使用了不同的 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];
} 

您正在使用 Storyboard,那么请尝试在 class1.h 中添加它并添加标识符 class2Segue到 Storyboard中的这个segue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"class2Segue"]) 
    {
        Class2 *tableController = (Class2 *)[segue destinationViewController];
        tableController.totalArray = self.savedArray;
    }
}

关于ios - 将另一个类的项目添加到另一个类的属性。 Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19511626/

相关文章:

ios - SpriteNode 不可见

ios - 如何在iOS中使用IAPHelper从应用程序商店获取最近购买的单个产品收据?

objective-c - 以编程方式更改时,UISwitch 不发送 valueChanged 事件

ios - 类不符合键的键值编码

ios - 在隐藏导航栏的 ViewController 之间跳转

mysql - 从未知时间戳转换为可读时间戳

iphone - "SHK.h"找不到文件

c++ - Xcode C++ 错误阻止进一步输出超过 srand()

xcode - 基础国际化和 "Could not find a storyboard named […]"

ios - SwiftUI 无法为图像过渡设置动画