好吧,我有一個小程序,它具有以下文件;
- HomeViewController(.H .M的.xib)
- DataViewController(.H .M的.xib)
- 的AppDelegate(.H .M)
- 人(.H .M)[對象]
+支持文件等...
在視圖控制器之間共享對象實例
假設我通過HomeViewController中的文本框和其他輸入獲取用戶輸入,並將它們設置爲Person(年齡,年級等)的實例的屬性,我如何從DataViewController訪問它們(同一實例)以顯示它們?
下面是代碼HomeViewController.h片段和.M
.H
@interface HomeViewController : UIViewController {
IBOutlet UIButton *done;
BOOL standardRes;
}
@property (nonatomic) int newAge;
@property (nonatomic) int newGrade;
-(IBAction)doneButtonPressed;
@end
.M
@implementation HomeViewController
@synthesize newAge, newGrade;
-(IBAction)doneButtonPressed{
Person *user = [[Person alloc]init]; //Creating an instance of Person called user
user.age = newAge; //Do I even need this if I use setters and getters in person.m?
user.grade = newGrade; //Do I even need this if I use setters and getters in person.m?
NSLog(@"Age: %i, Grade: %i", user.age, user.grade); //Testing with NSLog
newAge = 175;
[user setAge:(int)newAge]; //Calling setter method for property 'age' in Person.m
DataViewController *vc = [[DataViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
這裏是Person.h和一點點。 m
@interface Person : NSObject {
}
@property (nonatomic, getter = age, setter = setAge:) int age;
@property (nonatomic) int grade;
@end
@implementation Person
@synthesize age, grade;
-(void)setAge: (int) newAge {
age = newAge;
}
-(int)age {
return age;
}
@end
注:
- 使用導航控制器
- iOS 6的
- 的Xcode 4.5.1
+如果您需要任何更多的信息,讓我知道! :)
P.S.我有點新的這個東西所以這可能是一個愚蠢的問題;)
我試圖左右逢源,但對你HomeViewController.h改了行說有語法錯誤:「DataViewController」不可見@interface聲明的選擇「initWithPerson:」 – WillB
錯字:HomeViewController.m ...對不起:P – WillB
我很抱歉@WillB,我混了文件名。看我的編輯。 – WDUK