所以我有两个类。当按下保存按钮时,它将从 self.screen.text
传递值通过 addItem
totalArray
的方法在第 2 类。如果我尝试 NSLog
在 @implementation
的 addItem
方法,然后它会给出正确的输出,但如果我在 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/