我有两个视图控制器:BSViewController
其中包含源 ivarsnumber
和array
,以及BSotherViewController
作为目标需要接收 ivars 。这个问题提供了一种产生所需结果的方法。建议是计算 和 的值,并self.number
覆盖指定的值,如此处所示。self.array
init
init
- (id)init {
if (self = [super init]) {
//Set values
NSArray* _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
self.array = _array;
self.number = 25;
}
return self;
}
但我不知道这个解决方案如何使原始方法( )的计算成为self.number
可能;使用我尝试过的任何方法,我只能为它们的两个值获取 0 和 null 。self.array
viewDidLoad
viewDidLoad
此外,以下行会产生一个警告问题,view
即未使用的变量。
BSViewController *view = [[BSViewController alloc] init];
所以我正在寻找一种方法,它首先计算我的 ivars number
,array
然后执行,init(WithNumber)
以便可以在目标类中使用相同的变量BSotherViewController
。
我认为更直接的方法是不使用init
,而是使用类似以下的方法initWithNumber
,但我似乎无法满足使用下划线的所有 ARC 要求,以及我对objective-c 的有限理解。
- (id)initWithNumber:(NSInteger)number array:(NSArray *)array
{
self = [super init];
if (self) {
_number = number;
_array = array;
return self;
}
return nil;
}
为了完整起见,我将在下面重现上一个问题的答案中生成的大部分代码。
BSViewController.h
#import <UIKit/UIKit.h>
@interface BSViewController : UIViewController{
// NSInteger number;
}
@property (nonatomic) NSInteger number;
@property (nonatomic, weak) NSArray * array;
// - (id)initWithNumber:(NSInteger)number array:(NSArray *)array;
@end
BSViewController.m
#import "BSViewController.h"
@interface BSViewController ()
@end
@implementation BSViewController
@synthesize number;
@synthesize array;
/*
- (id)initWithNumber:(NSInteger)number array:(NSArray *)array
{
self = [super init];
if (self) {
_number = number;
_array = array;
return self;
}
return nil;
}
*/
- (id)init {
if (self = [super init]) {
NSArray* _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
self.array = _array;
self.number = 25;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"self: %@", self);
BSViewController *view = [[BSViewController alloc] init]; //Warning issued: unused variable
NSLog(@"self number: %d", self.number);
NSLog(@"self array: %@", self.array);
}
@end
BSotherViewController.h
#import <UIKit/UIKit.h>
@class BSViewController;
@interface BSotherViewController : UIViewController
@property (strong, nonatomic) BSViewController *aview;
@end
BSotherViewController.m
#import "BSotherViewController.h"
#include "BSViewController.h"
@interface BSotherViewController ()
@end
@implementation BSotherViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
BSViewController *aview = [[BSViewController alloc] init];
NSLog(@"other view: %@", self.aview);
NSLog(@"other number: %d", aview.number);
NSLog(@"other array: %@", aview.array);
}
@end