我想保持我的項目組織得更好,而不是將我的Appdelegate
與我想從viewcontroller
傳輸到viewcontroller
的數據重載,我想創建一個模型類來幫助保持組織更有條理。但是,使用模型時,我很難在控制器之間傳輸數據。嘗試將此nsstring數據從ViewController1
轉移到ViewController2
時,您能否告訴我我的方式有錯誤?附:我做了這個例子,因爲我的真實項目有點混亂,所以我提前爲任何不一致道歉。在NSLog
報告零以下結果需要幫助在ViewControllers之間傳輸數據
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 #進口
@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"]];
有沒有實現它的方式,其中的數據將被存儲在模型裏面串「@屬性(非原子,強)的NSString *字符串;」並且我不必在viewcontroller2中編寫字符串屬性?如果不是這樣,那我確實喜歡將數據保存在模型類中。 – user3192186
現在就是這樣。代碼中仍然不起作用的是你設置vcm的地方。如果你想將它設置在代碼的一部分(MyHandler)中,並在另一部分(tableView:didSelectRowAtIndexPath :)中使用它,你需要在ViewController1上創建一個屬性。 – Jesse
好的,我明白了。將實施它。 – user3192186