我想让我的项目更有条理,而不是将我想要从Appdelegate
转移到viewcontroller
的数据重载viewcontroller
我想创建一个模型类来帮助保持事情更有条理。但是,在使用模型时,我很难在控制器之间传输数据。在尝试将此nsstring数据从ViewController1
传输到ViewController2
时,您能告诉我我的方式错误吗?附:我做了这个例子,因为我的真实项目有点混乱所以我提前道歉任何不一致。以下结果导致NSLog
在
ViewController2.m
ViewController1.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
ViewController2 *viewController2 =[[ViewController2 alloc]init];
ViewControllerModel *vcm = [self.array objectAtIndex:indexPath.row];
NSLog(@"%@",vcm.string) // this will output a number
[self.navigationController pushViewController:viewController2 animated:YES];
}
// this delegate fetches an array of json data
-(void)fetchedResults:(NSMutableArray*)arrayList{
self.array = arrayList;
}
ViewController2.m
- (void)viewDidLoad
{
ViewControllerModel *vcm = = [[ViewController alloc] init];
[super viewDidLoad];
NSLog(@"%@",vcm.string); // this will output null.
}
ViewControllerModel .h #import
@interface ViewControllerModel : NSObject
@property (nonatomic, strong) NSString *string;
@end
ViewControllerModel.m
#import "ViewControllerModel.h"
@implementation ViewControllerModel
@synthesize string;
@end
MyHandler.m
//this is where vcm.string in ViewController1.m will get all the numbers not sure if this is needed but just in case .
for (NSDictionary *dict in responseArray)
{
ViewControllerModel *vcm = [[ViewControllerModel alloc] init];
vcm.string = ([dict valueForKey:@"string"] == [NSNull null]) ? @"" : [NSString stringWithFormat:@"%@",[dict valueForKey:@"string"]];
答案 0 :(得分:1)
进行以下更改:
ViewController1.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
ViewController2 *viewController2 =[[ViewController2 alloc]init];
ViewControllerModel *vcm = [ViewControllerModel alloc] init];
vcm.string = @"My String";
viewController2.vcm = vcm;
NSLog(@"%@",vcm.string) // this will output a number
[self.navigationController pushViewController:viewController2 animated:YES];
}
// this delegate fetches an array of json data
- (void)fetchedResults:(NSMutableArray*)arrayList{
self.array = arrayList;
}
ViewController2.h
@interface ViewController2 : NSObject
@property (nonatomic, strong) ViewControllerModel *vcm;
@end
ViewController2.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", self.vcm.string);
}
我还建议进行以下改进。
此时你真的不需要模型对象。您可以将字符串作为NSString属性添加到ViewController2而不是ViewControllerModel对象:
@property(非原子,复制)NSString * string;
我建议将属性,模型对象和视图控制器命名为更具描述性的内容。即使它是一个样本,如果你不这样做也很难理解它。
当你创建一个NSString属性(或任何其他具有可变等价物的类)时,我建议使用'copy'而不是'strong'。如果将NSMutableString分配给属性,这将成为字符串的不可变副本,这被认为是一种更安全的方法。