Objective-C處理Null 字元串和頁面傳值及自訂拷貝_IOS

來源:互聯網
上載者:User

Null 字元串
在ios應用中,如果從網路請求資料,返回json或者是xml格式的資料時,經常會遇到空串,一般介面是用java等語言寫的,如果是安卓,因為源語言都是java,只需判斷是否等於null即可,但是在ios中會出現各種各項的形式,比如null,(null),<null>。
如果單純用

複製代碼 代碼如下:

string!=nil;

無法判斷出角括弧的空串

完整判斷方法

複製代碼 代碼如下:

-(BOOL)isNull:(id)object
{
    // 判斷是否為空白串
    if ([object isEqual:[NSNull null]]) {
        return NO;
    }
    else if ([object isKindOfClass:[NSNull class]])
    {
        return NO;
    }
    else if (object==nil){
        return NO;
    }
    return YES;
}

對空串進行發訊息會出現各種各樣的崩潰,讓人很無語,同理轉換字串
複製代碼 代碼如下:

-(NSString*)convertNull:(id)object{
 
    // 轉換空串
 
    if ([object isEqual:[NSNull null]]) {
        return @" ";
    }
    else if ([object isKindOfClass:[NSNull class]])
    {
        return @" ";
    }
    else if (object==nil){
        return @"無";
    }
    return object;
    
}

頁面傳值和自訂拷貝
做網路相關的一些問題時,有時候值比較多,自訂個一個類,想把這個類的整個部分的值傳到另一個介面,這就涉及到拷貝問題,自訂的類裡一定要實現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。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.