iOS頁面間傳值及自定義類拷貝問題
作者:佚名
做網絡相關的一些問題時,有時候值比較多,自定義個一個類,想把這個類的整個部分的值傳到另一個界面,這就涉及到拷貝問題,自定義的類里一定要實現NSCopying協議,寫上拷貝的方法- (id)copyWithZone:(NSZone *)zone,這樣這個類才會像NSString類一樣,可以用=賦值拷貝。
自定義一個TypesItem類,繼承自NSObject,含有三個變量(可自定義添加多個)
TypesItem.h
- #import <Foundation/Foundation.h>
- @interface TypesItem : NSObject<NSCopying>
- {
- NSString *type_id;
- NSString *type_memo;
- NSString *type_name;
- }
- @property (nonatomic,copy) NSString *type_id;
- @property (nonatomic,copy) NSString *type_memo;
- @property (nonatomic,copy) NSString *type_name;
- @end
TypesItem.m文件中,除了要synthesize這三個變量之外
- @synthesize type_id,type_memo,type_name;
還要實現NSCopying協議方法
- (id)copyWithZone:(NSZone *)zone
- - (id)copyWithZone:(NSZone *)zone
- {
- TypesItem *newItem = [[TypesItem allocWithZone:zone] init];
- newItem.type_name = self.type_name;
- newItem.type_id = self.type_id;
- newItem.type_memo = self.type_memo;
- return newItem;
- }
頁面間傳值,假設A->B,A中的TypeItem的值要傳到B中
在B中.h文件寫上代碼
- @property(nonatomic,copy) TypesItem *selectedItem;
在B.m文件中
- @synthesize selectedItem;
在A.m中跳轉到B之前加上代碼
- BViewController *BVC = [[[BViewController alloc] initWithNibName:@"BViewController" bundle:nil] autorelease];
- // item為TypeItem類型,且不為空
- BVC.selectedItem = item;
- [self.navigationController pushViewController:BVC animated:YES];
PS:頁面間傳值時,此處的BVC.selectedItem中的BVC一定與push過去的BVC保持一致,否則push到B界面中的selectedItem值必定為null。
責任編輯:閆佳明
來源:
oschina